Subhojit
Subhojit

Reputation: 1541

How to update the value a component's state variable in another component in React.js?

I want to update the value of 'change_color' in the second class and automatically render it in the first class when the value gets changed. Assume, 'Second' component as the child of the 'First' component.

Solved it. Code is edited and it is the answer.

class First extends Component {
  constructor() {
     super();
     this.state = {
       change_color: false
     }
     this.handleChange = this.handleChange.bind(this);
  }
  handleChange() {
    this.setState({
       change_color: true
    })
  }
  render() {
   console.log(this.state.change_color);
   return(<div><Second colorChange={this.handleChange} /></div>)
  }
}

class Second extends Component {
  constructor() {
     super();
  }
  render() {
    return(<div><button onClick={this.props.colorChange} /></div>)
  }
}

Upvotes: 1

Views: 12775

Answers (2)

wzth
wzth

Reputation: 56

Maybe you can try this, just make a container component, and set the value you want to change into a state of the container component, add a method to change the state value, then, you can use "this.props.handleColorChange" to call the method of the parent component in children components.

class ParentComponent extends Component {
  constructor() {
     super();
     this.state = {
       change_color: false
     }
  }
  handleColorChange= () => {
    const {change_color} = this.state;
    this.setState = {
       change_color: !change_color
     }
  }
  render() {
   const {change_color} = this.state,
    {handleColorChange} = this;
   return (
   <div>
    <ChildComponent1
      color={change_color} 
      handleColorChange={handleColorChange}
    />
    <ChildComponent2 
      color={change_color} 
      handleColorChange={handleColorChange}
    />
   </div>
   );
  }
}

class ChildComponent1 extends Component {
  constructor() {
     super();
  }
  render() {
   const {color} = this.props;
   return(
    <span>now, the color is {color}</span>
   )
  }
}

class ChildComponent2 extends Component {
  constructor() {
     super();
  }
  const {handleColorChange} = this.props;
   return(
    <button onClick={handleColorChange}>click to change color</button>
   )
}

Upvotes: 2

Santiago Benitez
Santiago Benitez

Reputation: 362

What you need to do is lifting up the state. Create a new component that has a state with the colour and the change colour function. Then pass to first and second componentes the corresponding properties as props and inside of them call the function to change the colour. Does it makes sense?

Upvotes: 1

Related Questions