Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is getInitialState not being called for my React class?

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.

like image 213
ndbroadbent Avatar asked Jul 29 '15 19:07

ndbroadbent


People also ask

What is getInitialState in React?

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 .

What is the difference between using constructor vs getInitialState in React?

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).

How do you call a constructor in React?

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.

How do you call a ID in React?

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 .


1 Answers

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.

like image 170
ndbroadbent Avatar answered Sep 22 '22 03:09

ndbroadbent