uladzimir
uladzimir

Reputation: 5689

Open Select after a click on label

I'm looking for a way to open a Select (not native) component from Material UI after a click on the label with htmlFor specified.

<label htmlFor='menu'>Label to open Menu</label>

<MUISelect inputProps={{id: 'menu'}} native={false}>{options}</MUISelect>

Obviously it doesn't work

Upvotes: 3

Views: 5969

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81056

There are two main aspects to this problem:

  1. You need to get the id onto the same element that has the click-handler for opening the menu.
  2. The element with the click-handler is a div and not an input. Labels do not automatically trigger the click event of the labelled element when it is not an input element.

The first aspect can be solved by using SelectDisplayProps:

SelectDisplayProps={{ id: "menu" }}

The second aspect can be solved with a custom label component:

import React from "react";

const LabelForClickableDiv = ({ htmlFor, ...other }) => {
  const onClick = () => {
    document.getElementById(htmlFor).click();
  };
  return <label htmlFor={htmlFor} onClick={onClick} {...other} />;
};
export default LabelForClickableDiv;

Here's a working example:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";
import LabelForClickableDiv from "./LabelForClickableDiv";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

function SimpleSelect() {
  const classes = useStyles();
  const [value, setValue] = React.useState("");

  return (
    <>
      <form className={classes.root} autoComplete="off">
        <FormControl className={classes.formControl}>
          <LabelForClickableDiv htmlFor="menu">
            Label to open Menu
          </LabelForClickableDiv>
          <Select
            value={value}
            onChange={event => {
              setValue(event.target.value);
            }}
            SelectDisplayProps={{
              id: "menu"
            }}
          >
            <MenuItem value="">
              <em>None</em>
            </MenuItem>
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
        </FormControl>
      </form>
    </>
  );
}

export default SimpleSelect;

Edit Select with non-MUI label

Upvotes: 2

Related Questions