Expanding @ isaac-pak's answer, if you want to pass the default value to your component in props, you can keep it in the state in the componentDidMount () life cycle method to make sure that the default value is selected for the first time.
Please note I updated the following code to make it more complete.
export default class MySelect extends Component {
constructor(props) {
super(props);
this.state = {
selectedValue: '',
};
this.handleChange = this.handleChange.bind(this);
this.options = [
{value: 'foo', label: 'Foo'},
{value: 'bar', label: 'Bar'},
{value: 'baz', label: 'Baz'}
];
}
componentDidMount() {
this.setState({
selectedValue: this.props.defaultValue,
})
}
handleChange(selectedOption) {
this.setState({selectedValue: selectedOption.value});
}
render() {
return (
<Select
value={this.options.filter(({value}) => value === this.state.selectedValue)}
onChange={this.handleChange}
options={this.options}
/>
)
}
}
MySelect.propTypes = {
defaultValue: PropTypes.string.isRequired
};
source
share