Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set initial state with using ES6 class in React?

Tags:

reactjs

state

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.

like image 430
John Anisere Avatar asked Oct 12 '17 16:10

John Anisere


People also ask

How do you create an initial state in React?

There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.

How do you set initial state in functional component React?

Initializing state In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.

How do you set a state React class?

To update state , React developers use a special method called setState that is inherited from the base Component class. The setState method can take either an object or a function as the first argument.

How do you initialize a state in React with props?

To initialize state from props in a React component, we can watch the prop's value with the useEffect hook, then we can call the state setter function to set the state's value to the prop's value. to create the Child component with the text prop. We create the val state with the useState hook.


2 Answers

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?

like image 178
Jenna Rajani Avatar answered Oct 19 '22 15:10

Jenna Rajani


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:

  • Babel with constructor
  • Babel without constructor

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

like image 31
joeytwiddle Avatar answered Oct 19 '22 16:10

joeytwiddle