Reputation: 3411
How can I use the options in the select in my state?
this.state = {
posts: [],
question: '',
body: '',
postType: '',
}
<select value="types" className="u-full-width">
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
I am not sure how to set the state of postType based off what the user selects.
getPostType() {
const type =
this.setState({ postType: type });
}
Upvotes: 1
Views: 4104
Reputation: 586
You can try the following implementation.
class Sample extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
question: '',
body: '',
postType: 'Question',
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({postType: event.target.value});
}
render() {
return (
<form>
<label>
Select your postType:
<select className="u-full-width" value={this.state.postType}
onChange={this.handleChange}>
<option value="Question">Question</option>
<option value="Discussion">Discussion</option>
<option value="Clout">Clout</option>
</select>
</label>
</form>
);
}
}
ReactDOM.render(
<Sample />,
document.getElementById('root')
);
Upvotes: 0
Reputation: 876
You need to add a function to handle the changes on the select, save the value in the state and pass it to the select.
Something like this:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
postType: 'Option 1',
}
this.onChange = this.onChange.bind(this)
};
onChange(event){
this.setState({
postType: event.target.value
})
}
render() {
return (
<div>
<select value={this.state.postType} onChange={this.onChange} className="u-full-width">
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
{this.state.postType}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
This is called a controlled component. You can read more about it here.
Upvotes: 1
Reputation: 103
I think that what you're looking for is the following:
<select className="u-full-width"
onChange= this.handleOnChange.bind(this)
ref={value => this.refName = value}>
<option value="Option 1">Question</option>
<option value="Option 2">Discussion</option>
<option value="Option 3">Clout</option>
</select>
handleOnchange(e){
e.preventDefault(e);
const type = this.refName.value;
setState({postType: type});
}
Hope it was helpful!
Upvotes: 0