How does one programmatically 'open' a Material-UI Select field?
Look at the example https://material-ui.com/components/selects/#controlled-open-select
import React from 'react';import { makeStyles } from '@material-ui/core/styles';import InputLabel from '@material-ui/core/InputLabel';import MenuItem from '@material-ui/core/MenuItem';import FormControl from '@material-ui/core/FormControl';import Select from '@material-ui/core/Select';import Button from '@material-ui/core/Button';const useStyles = makeStyles((theme) => ({ button: { display: 'block', marginTop: theme.spacing(2), }, formControl: { margin: theme.spacing(1), minWidth: 120, },}));export default function ControlledOpenSelect() { const classes = useStyles(); const [age, setAge] = React.useState(''); const [open, setOpen] = React.useState(false); const handleChange = (event) => { setAge(event.target.value); }; const handleClose = () => { setOpen(false); }; const handleOpen = () => { setOpen(true); }; return ( <div> <Button className={classes.button} onClick={handleOpen}> Open the select </Button> <FormControl className={classes.formControl}> <InputLabel id="demo-controlled-open-select-label">Age</InputLabel> <Select labelId="demo-controlled-open-select-label" id="demo-controlled-open-select" open={open} onClose={handleClose} onOpen={handleOpen} value={age} onChange={handleChange} > <MenuItem value=""> <em>None</em> </MenuItem> <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> </div> );}
You could do it by accessing the DOM node of the down arrow button, and manually triggering a click event on it.
Example that works on Mac Chrome on the demo website, via the console, after adding a 'mySelect' id field to the select field DOM element for easier access:
// Initialize a click event (mouseup seem more cross browser)var evt = document.createEvent('MouseEvents');evt.initEvent('mouseup', true, false);// The down arrow elment is the only SVG element un the selectvar elm = document.querySelector('#mySelect svg')// Dispatch the event (reusable)elm.dispatchEvent(evt);
If this solution fits your code, you'll have to check the full cross browser/platform way to create te proper event, and to select the arrow element (querySelector
is not available everywhere, although it's quite OK now)