anonym
anonym

Reputation: 4850

How do I set the current component state from the data received as props from the parent component?

The data received from the Parent Component can be used in the render() method of the Child Component but clearly, it's not possible to set the state in the render method as it creates an infinite loop. How do I setState() from the data received in props from the parent? I might have missed something but I also tried all the life-cycle components without much success.

For example,

import React from 'react';

class Parent extends React.Component
{
  render()
  {
    let user = {name: John, age: 28};
    return(
      <Child user={user}>
    );
  }
}

class Child extends React.Component
{
  constructor()
  {
    super(props);
    this.state = { user: {} }
  }

  render()
  {
    const user = this.props.user;
    console.log(user); // --> [✓] Outputs {name: John, age: 28};
    // this.setState({ user }) // --> [✘] 

    return(
      <div></div>
    );
  }
}

How do I do this?

Upvotes: 0

Views: 53

Answers (3)

Piyush Dhamecha
Piyush Dhamecha

Reputation: 1515

Use componentWillReceiveProps

class Child extends React.Component
{
  constructor()
  {
    super(props);
    this.state = { user: {} }
  }

  componentWillReceiveProps(nextProps){
     if(this.state.user != nextProps.user){
         this.setState({ user:nextProps.user });
     }
  }
  render()
  {
    const user = this.props.user;
    console.log(user); // --> [✓] Outputs {name: John, age: 28};
    // this.setState({ user }) // --> [✘] 

    return(
      <div></div>
    );
  }
}

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104529

You need to use componentWillReceiveProps() lifecycle method, it will get called whenever any change happens to props values.

componentWillReceiveProps():

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

componentWillReceiveProps(newProps){
    /*compare new values and previous value first if they are not same then update the state*/
    if(condition)
       this.setState({users: newProps.users})
}

Upvotes: 1

Daniel Andrei
Daniel Andrei

Reputation: 2684

You can set the state initially in the constructor and then use the lifecycle method componentWillReceiveProps. You can read more about lifecycle methods here: http://busypeoples.github.io/post/react-component-lifecycle/

Upvotes: 1

Related Questions