Reputation: 146
I have two dropdowns, the second controlled by the first. When selecting a value in the first dropdown, it sets a new list of options for the second dropdown.
The problem I have is the selected index of the second dropdown is being remembered, and I don't see a clear way to set the selected index. If this was just javascript, I'd just set the selected index. But being react, I'm not sure what I should do.
render() {
let renderWorkItemTypes = (workItemType: TFS_WorkItemTracking_Contracts.WorkItemType) => {
return <option value={workItemType.name}>{workItemType.name}</option>;
};
return <select onChange={this.props.workItemTypeChanged}>{this.props.workItemTypes.map(renderWorkItemTypes) }</select>;
}
Upvotes: 4
Views: 14287
Reputation: 146
The issue was I was not also resetting the value when new props were coming in.
Final code:
class WorkItemTypeDropDown extends React.Component<IWorkItemTypeDropdownProps, any> {
constructor(props: IWorkItemTypeDropdownProps) {
super(props);
this.state = {
value: ""
};
}
componentWillReceiveProps(nextProps: IWorkItemTypeDropdownProps, nextContext: any) {
this.setState({
value: ""
});
}
onChange(e: React.FormEvent) {
let select = e.target as HTMLSelectElement;
let workItemType = select.options[select.selectedIndex].getAttribute("value");
this.setState({
value: workItemType
});
this.props.workItemTypeChanged(e);
}
render() {
let renderWorkItemTypes = (workItemType: TFS_WorkItemTracking_Contracts.WorkItemType) => {
return <option value={workItemType.name}>{workItemType.name}</option>;
};
return <select value={this.state.value} onChange={this.onChange.bind(this)}>{this.props.workItemTypes.map(renderWorkItemTypes) }</select>;
}
}
Upvotes: 0
Reputation: 11693
I advice you using the props value
of <Select>
as described by React:
<select value="B">
<option value="A">Apple</option>
<option value="B">Banana</option>
<option value="C">Cranberry</option>
</select>
When your onChange
triggers, edit your component state with setState
and change the <select>
value: <select value={this.state.value}>
? Having the select field value depending on your component state allows you to control the default value and therefore to change it when the first select field resets the second select field.
Upvotes: 4