Reputation: 3886
In the below code I have a simple react component which has a form containing a react-select component. It initially displays the defaultValue and then gives two options to select. Once selected the submit button would send a post request. Every thing works fine point the issue is that I want to revert the Select component to display the default value after on submit is clicked.
import Select from 'react-select';
export class Test extends Component {
this.setState = {
selection: 0,
};
onSelectChange = (e) => {
this.setState({ selection: e.value });
}
onSubmit = (e) => {
e.preventDefault();
const { selection } = this.state;
// Post request logic comes here
// Reset Select component to original default state
}
render() {
const defaultValue = { label: 'Choose something', value: 0 };
const options = [
{ label: 'Item 1', value: 1 },
{ label: 'Item 2', value: 2 },
];
return (
<form onSubmit={this.onSubmit}>
<Select
options={options}
defaultValue={defaultValue}
onChange={this.onSelectChange}
/>
//submit button here
</form>
);
}
}
Upvotes: 0
Views: 13669
Reputation: 1477
You can use component lifecycle methods also
componentWillReceiveProps(nextProps) {
After submitting the form, props will change
if (this.state.selection === nextProps.value && this.state.selection !== 0) {
this.setState({ selection: 0 });
}
Upvotes: 0
Reputation: 89
import Select from 'react-select';
export class Test extends Component {
this.setState = {
selection: 0,
};
onSelectChange = (e) => {
this.setState({ selection: e.value });
}
onSubmit = (e) => {
e.preventDefault();
const { selection } = this.state;
// Post request logic comes here
// Reset Select component to original default state
this.setState({selection: 0});
}
render() {
const options = [
{ label: 'Choose something', value: 0 },
{ label: 'Item 1', value: 1 },
{ label: 'Item 2', value: 2 },
];
return (
<form onSubmit={this.onSubmit}>
<Select
options={options}
value={this.state.selection}
onChange={this.onSelectChange}
/>
//submit button here
</form>
);
Use value prop instead of defaultValue and manage it through state.On Submit, reset that state to initial value i.e 0.
Upvotes: 3
Reputation: 3174
Since you're already using component state, all you have to do is add value = {this.state.selection}
as a prop on your <Select>
component. After your post statement(either using promise or async), do this.setState({selection: 0})
and it'll reset your <Select>
back to value 0.
Upvotes: 0