Reputation: 2763
I am using a component to do the Input of Select called SelectInput.
Here is my code:
'use strict'
import React from 'react'
class SelectInput extends React.Component{
constructor(props){
super(props);
this.state = {
select: "",
items: []
}
this.handleChange = this.handleChange.bind(this)
}
.
.
.
handleChange(event){
console.log(event.target.value)
this.setState({
select: event.target.value
});
if(this.props.onChange) {
this.props.onChange(event)
}
}
render(){
let disabled = this.state.items.length > 1 ? false : true,
selected = this.state.items ? this.state.items[0] : ""
return (
<select name={this.props.name} disabled={disabled} defaultValue={selected} value={this.state.select} onChange={this.handleChange}>
{this.state.items && this.state.items.map(item =>
<option value={item} >{item}</option>
)}
</select>
)
}
}
My problem is when my select has only one option, I disable the select and insert the value as default. But I dont get the value of event at onChange to pass to the parent component.
How do I do this?
Thanks in advance
Upvotes: 0
Views: 1878
Reputation: 26
I assume that if you want call thehandleChange
method even with one item is to having a state up-to-date or/and calling the handler onChange
passed by props.
At some point your state.items
must be populated :
componentWillMount(){
// load data (ajax or hard-coded)
let items = ['toto'];
let select = items.length ? items[0] : '';
this.setState({
items,
select
});
if(this.props.onChange) {
this.props.onChange(select);
}
}
I removed the selected
variable and the defaultValue
attribute in the render
method :
render(){
let disabled = this.state.items.length > 1 ? false : true;
return (
<select name={this.props.name} disabled={disabled} value={this.state.select} onChange={this.handleChange}>
{this.state.items && this.state.items.map((item, i) =>
<option key={i} value={item} >{item}</option>
)}
</select>
)
}
Upvotes: 1