Reputation: 951
I am new to React and I am trying to make a simple dynamic form with 3 selects.
My problem is that the options of child selects should be filled based on option selected in parent select.
Here is my code:
var MySelect = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
React.createElement(
'div',
{ },
React.createElement(
'select',
{ id: this.props.id,
onChange: this.change,
value: this.state.value
},
React.createElement("option", null, "Yes"),
React.createElement("option", null, "No"),
this.props.title
),
React.createElement(
'select',
{ id: this.props.id,
onChange: this.change,
value: this.state.value
},
React.createElement("option", null, "Author1"),
React.createElement("option", null, "Author2"),
this.props.title
),
React.createElement(
'select',
{ id: this.props.id,
onChange: this.change,
value: this.state.value
},
React.createElement("option", null, "Book1"),
React.createElement("option", null, "Book2"),
this.props.title
)
));
}
});
So if we select Yes, we have 2 authors, and if we select author1 - we can select only book1.
In case we select author2, we can select only book2 but not book1. If we select No, we cannot select any authors or books. I believe there should be something with states, but I still cannot get the point from the docs.
Upvotes: 1
Views: 54
Reputation: 13
I will explain with code. You could do the following. You could have 3 boolean states, one would be assigned to the select list of authors and other 2 to the individual option values(book1, book2). Based on what the users selects in the list- Yes or No. Consider the following code. Onchange handler of Yes/No select list
If(event.target.value=="Yes")
{
this.setState({AuthorsSelectable:true,
book1Selectable:true,
book2Selectable:true
});
}
else{
this.setState({AuthorsSelectable:false,
book1Selectable:false,
book2Selectable:false
});
}
Now you would in the onchange handler of Author1/Author2 list
if(event.target.value="Author1"){
this.setState({book1Selectable:true,
book2Selectable:false
});
}
else{
this.setState({
book1Selectable:false.
book2Selectable:true
});
Hope this helps.
Upvotes: 0
Reputation: 798
It's better to break it down into a flow of components than managing everything in a complex state machine in a single component.
You can extract the Author element logic to a new component. If the first select has a 'Yes', you render the Author component, otherwise not.
In the Author component, you should manage the author selected as a state and pass in that state to the Book component as a prop.
In the Book component, you can render the select menu options as per the author received in the props.
You'll also have to use componentWillReceiveProps
in Book component to keep track of changing props.
Upvotes: 1