Currently, Material-UI v1.0.0 does not have a selectField implemented yet so I am attempting to create my own version using TextField, Menu, and MenuItem Components.
Below is the code for my custom selectField:
export default class SelectField extends React.Component{
constructor(props){
super(props);
this.state = {
anchorEl: undefined,
open: false,
};
}
handleClick = event => {
this.setState({ open: true, anchorEl: event.currentTarget });
};
handleRequestClose = () => {
this.setState({ open: false });
};
handleMenuItemClick = (event, index) => {
this.setState({ open: false });
this.props.onChange(index);
};
render(){
const { style, name, label, value, onChange, children } = this.props;
return (
<div>
<TextField style={style} onClick={this.handleClick} type="text" name={name} label={label} value={value} InputProps={{ placeholder: label }} />
<Menu open={this.state.open} anchorEl={this.state.anchorEl} onRequestClose={this.handleRequestClose} >
{children.map((key) =>
<MenuItem key={key.value} selected={key.value === this.props.value} onClick={event => this.handleMenuItemClick(event, key. value)} >
{key.name}
</MenuItem>,
)}
</Menu>
</div>
);
}
}
One issue I encountered is with positioning the Menu. The Material-UI documentation suggests using the anchorEl property to position the menu in front of the opening element, which works well but becomes problematic when multiple items are selected. Additionally, I would like to adjust the menu's position to be below the TextField.
Another minor concern is setting the width of the menu to match the TextField's width and enabling search functionality within the Menu.