I have multiple Select in my application to get a specific value from dropdown(options). I created the select box as a an individual component with a state of select value and I would update the state on onChange using setState.
Select.js
class Select extends Component {
constructor(props){
super(props);
this.state = {
value: 'Select a planet'
}
this._handleChange = this._handleChange.bind(this)
}
_handleChange(e){
this.setState({
value: e.target.value
})
}
render() {
const { options, id, name, speed, value, onChange, vehicles } = this.props
return (
<div className="ff-select">
<select speed={speed} name={name} value={this.state.value} onChange={this._handleChange}>
{options.map((option,i) => {
return (
i === 0? <option value='Select a planet'>Select a planet</option>:
<option value={option.name}>{option.name}</option>
)
})}
</select>
</div>
)
}
};
export default Select;
How do I use this select in a parent component and update the parent state depends on the select value? Sounds weird right? I know that I can use props instead of state to solve the issue. But I just wanted to know what is the efficient method to use a select component in a parent component and communicate between them.
I hope the question is clear. Any kind of help would be appreciated Thank you!
Serdar Sanri
Sr. Frontend Developer
If you want to use it as a shared component you shouldn't care or think about parent component. It should be taken care of props. Simply you can pass onchange event by props and call this.props.onChange to pass selected value to parent l, then it should do whatever it wants with it.