I'm using ES6 classes with Babel. I have a React component that looks like this:
import { Component } from 'react'; export default class MyReactComponent extends Component { getInitialState() { return { foo: true, bar: 'no' }; } render() { return ( <div className="theFoo"> <span>{this.state.bar}</span> </div> ); } }
It doesn't look like getInitialState
is being called, because I'm getting this error: Cannot read property 'bar' of null
.
getInitialState is the ES5 friendly method to define the initial state of a React component. JavaScript React. One fairly popular question that got asked on programming bulletin boards has to do with the similarities and differences between React's constructor and the built in method getInitialState .
The constructor and getInitialState both in React are used to initialize state, but they can't be used interchangeably. The difference between these two is we should initialize state in the constructor when we are using ES6 classes and define the getInitialState method when we are using React. createClass (ES5 syntax).
In React, the constructor is called during component creation and before mounting. If you want to implement the constructor for a React component, call the super(props) method before any other statement. Otherwise, this. props will be undefined in the constructor and create bugs.
To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .
The developers talk about ES6 class support in the Release Notes for v0.13.0. If you use an ES6 class that extends React.Component
, then you should use a constructor()
instead of getInitialState
:
The API is mostly what you would expect, with the exception of getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With