15

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.

3

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

According to AST Explorer, this is called a ClassProperty.
After discovering this syntax, we considered using it for methods too, as an alternative to binding. However this article convinced us otherwise!
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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.