I have some forms in my redux app. I use redux-form-material-ui
as well. I'd like SelectFields that have just one option to be set by default to that option. Is the only way to do this by setting initialValues
while constructing the form component?
The solution is really simple. You just have to follow the redux-form
flow properly and call onChange
defined by Field
from redux-form
.
import React from 'react';
import { SelectField as MUISelectField } from "redux-form-material-ui";
export class SelectField extends React.Component {
constructor(props) {
super(props);
this.chooseSingleOption();
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.children !== this.props.children) {
this.chooseSingleOption();
}
}
chooseSingleOption() {
const children = React.Children.toArray(this.props.children);
if (children.length === 1) {
this.props.input.onChange(children[0].props.value);
}
}
render() {
return (
<MUISelectField {...this.props}/>
)
}
}