I'm having a heck of a time with Material UI's "Select" - about 10 hours into trying to get one working the way I'd like. I'd really appreciate some help.
This question is related to a previous one: Select MenuItem doesn't show when JSX saved to state and I suspect that if the "why" were answered on that, I might get a better idea of what's going on.
What I'm trying to accomplish is having a Select that does the following normal things:
These shouldn't be hard tasks, but I can't for the life of me get it. It' rather embarrassing.
Either way, I've currently got this JSX - effectively a cut-and-paste from the material ui demos with a map for the MenuItems
:
<FormControl className={classes.formControl}>
<InputLabel htmlFor={this.props.label}>{this.props.label}</InputLabel>
<Select
value={this.state.selectLabel}
onChange={this.handleSelectChange}
inputProps={{
name: 'selectLabel',
id: this.props.label,
}}
>
{this.props.value.map(valueLabelPair =>
<MenuItem
key={this.props.XMLvalue + "_" + valueLabelPair.label}
value={valueLabelPair.value}
>
{valueLabelPair.label}
</MenuItem>
)}
</Select>
</FormControl>
the handleSelectChange looks like this -- again, exactly the same as the material UI demo.
handleSelectChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
This kind of works except the console gives me the following error:
Failed prop type: The prop
value
is marked as required inSelectInput
, but its value isundefined
.
and the selected option and question label go on top of each other after you click away, like so:
Further, if I try to add in this code (in the componentDidMount function) with the goal of being able to pass in the 'selected'/default option...
componentDidMount() {
for (var i = 0; i < this.props.value.length; i++) {
if(this.props.value[i].selected) {
// *works* console.log("selected found: " + this.props.value[i].label);
this.setState({selectLabel:this.props.value[i].label});
}
}
}
it does not update the give me a default answer and also gives me the following additional error in the console (in addition to all issues above):
Warning: A component is changing an uncontrolled input of type hidden to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
What am I missing?
Just define selectLabel into constructor:
constructor () {
super()
this.state = {
selectLabel:'',
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With