Categories
React Answers

How to pass the initial state while rendering a component with React?

Spread the love

To pass the initial state while rendering a component with React, we set the prop value as the value of the state’s initial value in getInitialState.

For instance, we write

class C extends Component {
  //...
  getInitialState() {
    return { foo: this.props.foo };
  }
  //...
}

to set the initial value of the foo state to the foo prop’s value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *