Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - this.props looks undefined

I'm going through a React tutorial. Here's the code that doesn't work when I add a property to a Greeter object

let Greeter=React.createClass({
    render: ()=>{
      let name=this.props.name;
      return (<div>
      <h1>Hello {name}!</h1>
    </div>);
  }
});



ReactDOM.render(
  <Greeter name ="Your name"/>,
  document.getElementById("app")
);

The doesn't render at all, when I'm using Firefox, here's what I get:

unreachable code after return statementbrowser.min.js:37:6409 TypeError: undefined has no properties

like image 284
alt-ja Avatar asked Nov 06 '16 18:11

alt-ja


People also ask

Why my props is undefined react?

The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.

Why is Prop value undefined?

The "cannot set property 'props' of undefined" error occurs when we add an extra set of parenthesis when declaring a class component in React. js. To solve the error, remove the parenthesis after Component in your class declaration, e.g. class App extends Component {} .

How do you deal with an undefined react?

To check for undefined in React, use a comparison to check if the value is equal or is not equal to undefined , e.g. if (myValue === undefined) {} or if (myValue !== undefined) {} . If the condition is met, the if block will run.


1 Answers

The reason why this does not work is because you use an arrow function, inside an ES5 component. this is then undefined due to the arrow function, per the MDN documentation for arrow functions:

An arrow function expression has a shorter syntax compared to function expressions and does not bind its own this, arguments, super, or new.target. (emphasis mine)

React does something called 'autobinding' which automatically binds this for your functions in a component to refer to the component. But because you are using an arrow function, binding does not work (due to the fact, as mentioned earlier, arrow functions do not bind this). That means this is not bound thus it is undefined in your render function. This causes the error as undefined does not have any properties.

The solution is to use a regular function instead of an arrow function with React's autobinding:

render: function() {
    //...
}

React autobind's this so that it refers to the component in functions so it will work fine. If you are using ES6, you can use an ES6 method like so:

render() {
    //...
}

This is just syntactical sugar in ES6 for a regular function, and binding will occur. Thus, this will refer to the component, not undefined and will have receive props correctly.

like image 80
Andrew Li Avatar answered Sep 25 '22 08:09

Andrew Li