0

I am using props in react. And found this

var App = React.createClass({


        render: function(){
            var t = this.props.txt;
            return(<div>
                    <h1> {t}</h1>

                </div>);

        },

    });

    React.render(<App txt="hi"/>, document.body);

This works fine, as variable t is inside the render function. But when placed t outside the render function like this

var App = React.createClass({
// position of t is shifted here
    var t = this.props.txt;
        render: function(){

            return(<div>
                    <h1> {t}</h1>

                </div>);

        },

    });

    React.render(<App txt="hi"/>, document.body); 

This does not work. Since I am invoking App directly in React.render not the function render, I expect that App should have props available. What am I missing?

2
  • App is a class right? I am instantiating class in render method. @FelixKling Commented Jun 24, 2015 at 5:57
  • Yeah, kind of. The last line is not the problem. Commented Jun 24, 2015 at 5:59

1 Answer 1

3

I'm not quite sure why you expect this to work. That's just invalid JavaScript. You cannot put a variable declaration inside an object literal. Simplified example of what you are doing:

var foo = { var bar = 42; };

This is a syntax error. I recommend to read a JavaScript tutorial to learn more about objects.

Sign up to request clarification or add additional context in comments.

11 Comments

var a ={ function v(){ var x =5; } } Even this seems to be give an error
Well, similar reason: You cannot have a function declaration inside an object literal. The syntax of an object literals is {key: value, key: value, ...}. Check out the links.
So let's see, as you said App is an object and render is a function. If a variable declaration inside App is invalid .I declared var t inside render. So it should be invalid too as we agreed
I didn't say that App is an object, but you are passing an object to React.createClass. And yes, render is a function. Honestly, I suggest to get a better understanding of JavaScript first before you take on React...
Maybe you were referring to your first comment. The problem with var a = { function v(){ var x =5; } } is not the variable declaration but the function definition. You are not following the {key: value} pattern. You just wrote {value}. var a = { b: function v(){ var x =5; } } would be valid. And again, this has nothing to do with React. That's all JavaScript basics. Maybe you find this helpful as small introduction to a couple of important topics: felix-kling.de/jsbasics
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.