14

I have created the below class

class App extends Component{
     render() {
         return (
             <div className="app"></div>
         );
     }
}

How do i set initial state?
getInitialState() isn't working? what am i doing wrong?
The react docs are also not helping.

syam
  • 799
  • 1
  • 12
  • 30
John Anisere
  • 513
  • 1
  • 3
  • 13
  • 2
    check react doc [How to set initial state in es-6 class component](https://reactjs.org/docs/react-component.html#constructor) – Mayank Shukla Oct 12 '17 at 16:43
  • 1
    Also see: https://stackoverflow.com/q/37782403/1531971 This looks like a duplicate. –  Oct 12 '17 at 17:25
  • 1
    Possible duplicate of [set initial react component state in constructor or componentWillMount?](https://stackoverflow.com/questions/37782403/set-initial-react-component-state-in-constructor-or-componentwillmount) – Angel Cuenca Oct 12 '17 at 21:31

2 Answers2

26

There is also a shortcut of Jenna's great answer, which doesn't use constructor or this:

class App extends Component {
    state = {
        text: 'Hello World'
    };

    render() {
        return (
            <div>
                {this.state.text}
            </div>
        );
    }
}

A simplified example shows that the output is the same in both cases:

But if we extend a parent class, the transpiled output does differ, since the number of arguments in the constructor is unknown.

joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
  • According to [AST Explorer](https://astexplorer.net/#/gist/9a82ca465ae47f4273c65ad3fb87fd27/59607892ef56715fd0c75f3d45f094a676a9a3ff), this is called a ClassProperty. – joeytwiddle Feb 01 '18 at 10:15
  • After discovering this syntax, we considered using it for methods too, as an alternative to binding. However [this article](https://medium.com/@charpeni/arrow-functions-in-class-properties-might-not-be-as-great-as-we-think-3b3551c440b1) convinced us otherwise! – joeytwiddle May 23 '18 at 02:53
17
import React, { Component } from 'react';

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            text: 'Hello World'
        };
    }
    render() {
        return (
            <div>
                {this.state.text}
            </div>
        );
    }
}

You may also want to check out this post about the difference between when to use a constructor and when to use getInitialState.

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

Jenna Rajani
  • 243
  • 2
  • 3