0

enter image description hereI'm very new to material ui react . I tried creating select options dynamically but couldn't succeed , is there any way different method to create select options dynamically. I tried to create codesandbox but couldn't due to some error.Below is my code. Please help.

import React from "react";
import { Theme, useTheme } from "@mui/material/styles";
import ReactDOM from "react-dom";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, { SelectChangeEvent } from "@mui/material/Select";

const age = ["Ten", "Twenty", "Thirty"];
export const SelectBa = ({}) => {
  const theme = useTheme();
  const [personName, setPersonName] = React.useState([]);

  const handleChange = (event: SelectChangeEvent<typeof personName>) => {
    const {
      target: { value }
    } = event;
    setPersonName(typeof value === "string" ? value.split(",") : value);
  };

  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }} size={size}>
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={personName}
          onChange={handleChange}
          input={<OutlinedInput label="Name" />}
        >
          {age.map((age) => (
            <MenuItem
              key={age}
              value={age}
              style={getStyles(age, personName, theme)}
            >
              {age}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
};

ReactDOM.render(<SelectBa />, document.querySelector("#app"));
7
  • I realize that you are using the same name to render the list. Replace the list name age with ages. const ages = ["Ten", "Twenty", "Thirty"]; Also, include the error console message in the description Commented Sep 30, 2022 at 18:48
  • The above code is working fine ,my mistake I added age twice, but i would like to know is there any other way to achieve this dynamic select options. Thanks for the reply Commented Sep 30, 2022 at 19:04
  • @FábioRibeirodeCarvalho without defining const age [ten, twent] , is it possible to achieve. Because different user may different data, it should be dynamic generated not hard-coded. Thanks Commented Sep 30, 2022 at 19:23
  • Exactly what do You mean by "create select options dynamically"? Commented Oct 1, 2022 at 17:10
  • @HamedSiaban without hard coding the options ,can I do it dynamically? Commented Oct 2, 2022 at 5:08

1 Answer 1

1

You should have Your options in a state and then update it with user inputs.

import React from "react";
import { Theme, useTheme } from "@mui/material/styles";
import ReactDOM from "react-dom";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import { Button, OutlinedInput, TextField } from "@mui/material";

const SelectBa = ({}) => {
  const theme = useTheme();
  const [personName, setPersonName] = React.useState([]);
  const [ageList, setAgeList] = React.useState(["Ten", "Twenty", "Thirty"]);
  const [newAge, setNewAge] = React.useState("");

  const handleChange = (event: SelectChangeEvent<typeof personName>) => {
    const {
      target: { value },
    } = event;
    setPersonName(typeof value === "string" ? value.split(",") : value);
  };

  return (
    <div>
      <TextField
        id="outlined-name"
        label="Name"
        value={newAge}
        onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
          setNewAge(event.target.value)
        }
      />
      <Button
        onClick={() => {
          newAge && setAgeList([...ageList, newAge]);
          setNewAge("");
        }}
      >
        Add option
      </Button>
      <FormControl sx={{ m: 1, width: 300 }} size="medium">
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={personName}
          onChange={handleChange}
          input={<OutlinedInput label="Name" />}
        >
          {ageList.map((age) => (
            <MenuItem
              key={age}
              value={age}
              // style={getStyles(age, personName, theme)}
            >
              {age}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
};
export default SelectBa;

User will type the new option in the first TextField and by pressing the Button, the value will add to the options list.

Sign up to request clarification or add additional context in comments.

8 Comments

But this will be autocomplete component, I'm building select component which can be reusable. Is it possible to achieve it? Thanks
Unfortunately I can't understand what You want exactly. Can You express it with some images?
Added image above, my requirement is i have added values const age = ["Ten", "Twenty", "Thirty"]; which is hardcoded, I want user to add it according to their requirement. which means these values should be generated dynamically using material ui.
I think the updated answer will solve Your problem.
@ I'm really Thankful for your reply. But i want only the select component without any button added to it. Thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.