简体   繁体   中英

MUI select with label without the select having an ID

I have a material ui react select in a component that may be on a page multiple times.

In the examples all labelled selects use InputLabel with htmlFor that must be the id of the select.

I cannot give the select an id because id has to be unique for a page and this is a component that doesn't need to know all the id's on the page (nor anywhere in my code do I want to know about all the id's in the page).

According to the InputLabel documentation it doesn't even have a documented htmlFor propery.

Is it possible to label a MUI select without giving it an id?

So long as you don't run into any styling difficulties with your nested solution, then that is perfectly fine, but here's an example using a generated id that would allow you to avoid nesting the Select within the InputLabel:

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";

let nextIdSuffix = 1;

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

const CustomSelect = () => {
  const idRef = React.useRef();
  const classes = useStyles();
  const [value, setValue] = React.useState("");
  if (!idRef.current) {
    idRef.current = `CustomSelect${nextIdSuffix}`;
    nextIdSuffix++;
  }
  return (
    <FormControl className={classes.formControl}>
      <InputLabel htmlFor={idRef.current}>Age</InputLabel>
      <Select
        value={value}
        onChange={e => setValue(e.target.value)}
        inputProps={{
          name: idRef.current,
          id: idRef.current
        }}
      >
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    </FormControl>
  );
};
export default CustomSelect;

编辑生成的选择ID

Same as the html label tag ; I did the nested the Select in the InputLabel:

<InputLabel className="paging">
  Page:
  <Select
    value={current}
    onChange={e => changePage(e.target.value)}
    inputProps={{
      name: 'page',
      id: 'page',
    }}
  >
    {options.map(option => (
      <MenuItem key={option} value={option}>
        {option}
      </MenuItem>
    ))}
  </Select>
</InputLabel>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM