React: this.state Is Undefined

I ran into this today, so I’m writing it down in case it helps someone else.

Running something like the following, I found that this.state was undefined during render.

1
2
3
4
5
6
7
8
9
class MyComponent extends Component {
  getInitialState() {
      return { count: 0 };
  }

  render() {
      return <div>{this.state.count}</div>; // Error: this.state is undefined
  }
}

After a little searching, I found the release notes for React 0.13.0-beta-1, where they explained that ES6 classes should set initial state in the constructor, rather than defining a getInitialState method.

1
2
3
4
5
6
7
8
9
class MyComponent extends Component {
  constructor() {
      this.state = { count: 0 };
  }

  render() {
      return <div>{this.state.count}</div>; // Yay, it works!
  }
}

Pretty simple, but not immediately obvious if you don’t know about it.

I am now accepting new clients for part-time consulting and software development projects. Learn more

I haven't configured comments for this blog, but if you want to get in touch, you can find me on Twitter