Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating child's state from parent component

Let's say that my parent component got two child component :

Parent
| Child1
| Child2

I'am getting an input from Child2 and I'am passing it to the Parent component (until now, I know how to do). But then I need to pass that input to Child1 to update it's state.

How can I do that?

like image 424
Mit Avatar asked May 01 '17 11:05

Mit


2 Answers

You can have a function in your child component that updates the state based on the value sent from the parent component. And you can access a function of the child component form the parent component using refs

Example

Parent:

class Parent extends React.Component {
     funcUpdateChild1 = () => {
          this.child1.updateState('value here');
     }
     render() {
          return (
              <Child1 ref={(ip) => {this.child1 = ip}} />
              <Child2 ref={(ip) => {this.child2 = ip}} />
         ) 
     }
}

Child1

class Child1 extends React.Component {
     updateState = (value) => {
         //use the value to set state here
     }
     render() {
          return (
              //child1 contents here
         ) 
     }
}
like image 95
Shubham Khatri Avatar answered Nov 15 '22 20:11

Shubham Khatri


Hope you can get the main idea - create a function in the Parent component that will change the value passed to the Child1. ReactJS: Why is passing the component initial state a prop an anti-pattern?

class Parent extends Component {
  constructor(props){
    super(props);
    this.state = {
      value: ""
    }
  }
  changeValue(value){
    this.setState({value});
  }
  render(){
    return (
      <div>
          <Child1 value={this.state.value}/>
          <Child2 changeValue={changeValue}/>
      </div>
    )
  }
}


class Child2 extends Component {
  constructor(props) {
    super(props);
    this.state={
      input: ""
    }
  }
  handleChange(e){
    var {value} = e.target;
    this.setState({
      input: value
    },() => this.props.changeValue(value));
  }
  render(){
    return (
      <div>
          <input value={this.state.input} onChange={this.handleChange}/>
      </div>
    )
  }
}



class Child1 extends Component {

  constructor(props) {
    super(props);
    this.state={value:''}
  }
  componentWillReceiveProps(nextProps) {
    this.setState({value: nextProps.value})
  }


  render(){
    return (
      <div>
          {this.props.value}
      </div>
    )
  }
}
like image 20
kurumkan Avatar answered Nov 15 '22 19:11

kurumkan