Ad

Preselect An Element From The List Of Elements In Material-UI Select Component

- 1 answer

I want to preselect the element with the id 3 of my list. If I don't provide a preselected element it should automatically show the disabled item. Currently, the select box only shows Choose your option and if I try to pass down alreadySelected it's not working and I can't change my option later.

My app component:

import React from "react";
import ReactDOM from "react-dom";

import CustomSelect from "./components/Select";

function App() {
  const [selectElement, setSelectElement] = React.useState(0);

  // This element should be passed somehow down to the select component
  const alreadySelected = 3;

  return (
    <div className="App">
      <CustomSelect
        selectElement={selectElement}
        setSelectElement={setSelectElement}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

My select component:

import React from "react";
import * as PropTypes from "prop-types";
import { FormControl, InputLabel, MenuItem, Select } from "@material-ui/core";

function CustomSelect(props) {
  const { selectElement, setSelectElement } = props;

  const list = [
    {
      id: 1,
      name: "test 1"
    },
    {
      id: 2,
      name: "test 2"
    },
    {
      id: 3,
      name: "test 3"
    }
  ];

  function handleChange(event) {
    setSelectElement(event.target.value);
  }

  return (
    <FormControl fullWidth>
      <InputLabel htmlFor="qualification-type">Select box</InputLabel>
      <Select value={selectElement} onChange={handleChange}>
        <MenuItem disabled value={0}>
          <em>Choose your option</em>
        </MenuItem>
        {list.map(item => (
          <MenuItem key={`type-${item.id}`} value={item.id}>
            {item.name}
          </MenuItem>
        ))}
      </Select>
    </FormControl>
  );
}

CustomSelect.propTypes = {
  selectElement: PropTypes.number.isRequired,
  SetSelectElement: PropTypes.func.isRequired
};

export default CustomSelect;
Ad

Answer

useState hook accepts default value as param. You have give 0 as default. Instead:

Use your state default value as 3: const [selectElement, setSelectElement] = React.useState(3);

Yiu can even dynamically derive and pass as default value to state. Let me know.

Ad
source: stackoverflow.com
Ad