ndbroadbent
ndbroadbent

Reputation: 13803

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.

Upvotes: 33

Views: 11196

Answers (3)

CpILL
CpILL

Reputation: 6999

To expand a bit on what it means

getDefaultProps and propTypes are really just properties on the constructor.

the "on the constructor" bit is weird wording. In normal OOP language it just means they are "static class variables"

class MyClass extends React.Component {
    static defaultProps = { yada: "yada" }
    ...
}

or

MyClass.defaultProps = { yada: "yada" }

you can also refer to them within the class like:

constructor(props) {
    this.state = MyClass.defaultProps;
}

or with anything you declare as a static class variable. I don't know why this is not talked about anywhere online with regards to ES6 classes :?

see the docs.

Upvotes: 2

Des Horsley
Des Horsley

Reputation: 1888

Code to accompany Nathans answer:

import { Component } from 'react';

export default class MyReactComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      foo: true,
      bar: 'no'
    };
  }

  render() {
    return (
      <div className="theFoo">
        <span>{this.state.bar}</span>
      </div>
    );
  }
}

Upvotes: 31

ndbroadbent
ndbroadbent

Reputation: 13803

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.

Upvotes: 60

Related Questions