Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select handle onChange with props

I am using react-select in a child component but wanting to store the Select value in a state in the parent.

I appreciate that I have to store onChange in state and then pass this to the Select value, but I would like to keep this temporary onChange state in the child component not the parent.

So the question is how do I set the parent state (coming in on a prop) from the onChange state in the child.

Parent Component

campaignName (campaign){
  //will setState here
   console.log(campaign)
  }
...
<FormGroup>
  <Campaign
    campaignName={this.campaignName.bind(this)}
    campaignOptions={code in here that sets option}
   />
</FormGroup>

Child Component

updateValue (newValue) {
    this.setState({
        selectValue: newValue,
  // how do I set the parent state from this 
    });

<Select
   onChange={this.updateValue}
   value={this.props.campaignName}
   options={this.props.campaignOptions}
/>
like image 878
Nick Wild Avatar asked Apr 22 '26 08:04

Nick Wild


1 Answers

Pass the function directly from parent to child that will handle the onChange:

Parent Component

handleSelect(e) {
   this.setState({
       selectValue: e.target.value,
   });
}

render() {
    <ChildComponent selectOnChange={this.handleSelect} />
}

Child Component

<Select
   onChange={this.props.selectOnChange}
   value={this.props.campaignName}
/>

OR (if you want the method to stay on the child)

updateValue(e) {
   this.props.selectOnChange(e); //call the passed props here
}

<Select
   onChange={this.updateValue}
   value={this.props.campaignName}
/>
like image 153
Tenten Ponce Avatar answered Apr 24 '26 20:04

Tenten Ponce