How to fix the select value is always out of range error with React Material UI?

Sometimes, we want to fix the select value is always out of range error with React Material UI.

In this article, we’ll look at how to fix the select value is always out of range error with React Material UI.

How to fix the select value is always out of range error with React Material UI?

To fix the select value is always out of range error with React Material UI, we should make sure the value is a primitive value or the same object reference of the object as the selected value.

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("");
  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, val]] = Object.entries(element);
          return (
            <MenuItem value={val} key={key}>
              {key}
            </MenuItem>
          );
        })}
      </Select>
    </div>
  );
}

to render the MenuItem by calling followers.map with a function that takes the key and val from each element entry with Object.entries.

Then we set the value prop of MenuItem to val.

And the key is used as the value of the key prop and it’s also displayed as the text of the choice to the user.

Then to get the selected value and display it, we set the onChange prop to handleChange and the value prop to value.

We call setValue with event.target.value in handleChange to set the value state to the selected choice, which is the MenuItem‘s value prop’s value.

Conclusion

To fix the select value is always out of range error with React Material UI, we should make sure the value is a primitive value or the same object reference of the object as the selected value.