Categories
React Answers

How to set the default value in React Material-UI select box?

Spread the love

Sometimes, we want to set the default value in React Material-UI select box.

In this article, we’ll look at how to set the default value in React Material-UI select box.

How to set the default value in React Material-UI select box?

To set the default value in React Material-UI select box, we can set the initial value of the state that we use as the Select‘s value prop’s value.

The initial value must match one of the value prop of values of MenuItem.

For instance, we write:

import React from "react";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";

const followers = [
  { "0-50k": [0, 50000] },
  { "50k-100k": [50001, 100000] },
  { "100k-250k": [100001, 250000] },
  { "250k-500k": [250001, 500000] },
  { "500k-750k": [500001, 750000] },
  { "+1M": [750001, Number.MAX_SAFE_INTEGER] }
];

export default function App() {
  const [value, setValue] = React.useState("50k-100k");
  const handleChange = (event) => setValue(event.target.value);

  return (
    <div>
      <Select
        fullWidth
        id="followers"
        labelId="followersL"
        margin="dense"
        displayEmpty
        name="followers"
        onChange={handleChange}
        value={value}
        variant="outlined"
      >
        {followers.map((element) => {
          const [[key]] = Object.entries(element);
          return (
            <MenuItem value={key} key={key}>
              {key}
            </MenuItem>
          );
        })}
      </Select>
    </div>
  );
}

to define the value state with useState.

We set value‘s initial value to "50k-100k".

Next, we set Select‘s value prop to the value state.

Then when we add the MenuItems, we set the value prop of the MenuItem to key so that the 2nd entry matches the initial value of the value prop.

Conclusion

To set the default value in React Material-UI select box, we can set the initial value of the state that we use as the Select‘s value prop’s value.

The initial value must match one of the value prop of values of MenuItem.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *