Is there a way to deactivate specific options within the "Select" component on Material-UI, similar to how it is done in the "Autocomplete" feature?

Is it possible to restrict certain options in the Select component similar to how it is done in the Autocomplete component?

PS: The options are present in an array.

 <FormControl variant="outlined">
        <InputLabel>States</InputLabel>
        <Select native
          defaultValue=""
          // value={value}
          onChange={inputEvent}
          label="States"
        >
          {fetchedStates.map((states, i) => (
            <option key={states + i} value={states}>
              {states}
            </option>
          ))}
        </Select>
      </FormControl>

https://i.sstatic.net/TEQ93.png

Answer №1

To enable the Select to have disabled items, you can add the disabled property to the respective MenuItem (as demonstrated with the "Twenty" MenuItem in the example below).

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

const useStyles = makeStyles(theme => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

export default function SimpleSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState("");

  const handleChange = event => {
    setAge(event.target.value);
  };

  return (
    <div>
      <FormControl variant="outlined" className={classes.formControl}>
        <InputLabel id="demo-simple-select-outlined-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-outlined-label"
          id="demo-simple-select-outlined"
          value={age}
          onChange={handleChange}
          label="Age"
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem disabled value={20}>
            Twenty
          </MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}

https://codesandbox.io/s/disabled-menuitem-fvgi8?fontsize=14&hidenavigation=1&theme=dark

For a basic Select, you should utilize the disabled attribute for each <option>:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles(theme => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

export default function SimpleSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState("");

  const handleChange = event => {
    setAge(event.target.value);
  };

  return (
    <div>
      <FormControl variant="outlined" className={classes.formControl}>
        <InputLabel id="demo-simple-select-outlined-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-outlined-label"
          id="demo-simple-select-outlined"
          value={age}
          onChange={handleChange}
          label="Age"
          native
        >
          <option aria-label="None" value="" />
          <option value={10}>Ten</option>
          <option disabled value={20}>
            Twenty
          </option>
          <option value={30}>Thirty</option>
        </Select>
      </FormControl>
    </div>
  );
}

https://codesandbox.io/s/disabled-option-flswf?fontsize=14&hidenavigation=1&theme=dark

If your options are contained within an array, there should be a mechanism to identify which options need to be disabled. The following illustration presents one approach where option data includes a flag for disabling the option.

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles(theme => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

const options = [
  { value: 10, label: "Ten" },
  { value: 20, label: "Twenty", disabled: true },
  { value: 30, label: "Thirty" }
];

export default function SimpleSelect() {
  const classes = useStyles();
  const [age, setAge] = React.useState("");

  const handleChange = event => {
    setAge(event.target.value);
  };

  return (
    <div>
      <FormControl variant="outlined" className={classes.formControl}>
        <InputLabel id="demo-simple-select-outlined-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-outlined-label"
          id="demo-simple-select-outlined"
          value={age}
          onChange={handleChange}
          label="Age"
          native
        >
          <option aria-label="None" value="" />
          {options.map(option => (
            <option value={option.value} disabled={option.disabled}>
              {option.label}
            </option>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

https://codesandbox.io/s/disabled-option-7l0bl?fontsize=14&hidenavigation=1&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React: Managing various browsers and browser tabs to prevent duplicate operations

On my webpage, I have a button labeled Submit that, when clicked, triggers an operation by calling an API. After the button is clicked, it should be disabled or changed to reflect that the operation has started. I am facing an issue where multiple browser ...

The element in the iterator in next.js typescript is lacking a necessary "key" prop

Welcome to my portfolio web application! I have created various components, but I am facing an issue when running 'npm run build'. The error message indicates that a "key" prop is missing for an element in the iterator. I tried adding it, but the ...

What causes my useEffect hook to trigger twice in React?

I'm currently utilizing @preact/signals-react in my react project for integration purposes. Encountered a challenge that requires resolution. Interestingly, I discovered that by removing import { signal } from '@preact/signals-react', the ...

Creating endless loops in React NextJs using custom hooks OREndless looping in

Hey there! I'm currently facing an issue with a customHook inside a service that is being used on a page. When I use useRouter to get the query parameter, it results in an infinite loop. I attempted to resolve this by using useCallback, but even with ...

The conditional rendering issue in Mui DataGrid's renderCell function is causing problems

My Mui DataGrid setup is simple, but I'm encountering an issue with the renderCell function not rendering elements conditionally. https://i.sstatic.net/MEBZx.png The default behavior should display an EditIcon button (the pencil). When clicked, it t ...

Seeing <br> elements being inserted into a <div> element in the page source

I have encountered an issue where my code does not contain any br tags between the beginning of the div tag and table tag, but when I view the source, several br elements appear. Below is the code snippet from a .php file: <div id='tx_addAccountp ...

Creating a dynamic and adaptive horizontal SVG line for your website

Understanding how SVGs function is still a bit unclear to me. I know that the viewBox property plays a role in scaling SVGs, and I have come across advice suggesting not to specify height and width attributes when creating responsive SVGs. While there are ...

When bootstrap buttons are displayed inside a Vue component, there should be no spacing between them

Is this issue specific to the vue-loader or is it more related to webpack builds in general? Consider a basic HTML page with Bootstrap 4 loaded and two buttons added: <button type="button" class="btn btn-primary">Primary</button> <button t ...

Adding up rows and columns using HTML

I've designed an HTML table to function as a spreadsheet, with the goal of being able to total up rows and display the sum in a cell labeled "Total." The same calculation should be applied to columns as well, with totals displayed in the last column c ...

Ways to center an image without relying on margin or padding to achieve alignment

Is it possible to center all tags except for the img without using margins or paddings? header { display: flex; flex-direction: column; align-items: center; } .logo { border-radius: 50%; width: 100px; height: 100px; margin: 10px 0 0 10px; ...

Problem with Bootstrap container-fluid overlapping with floated element

I am struggling with the layout of my card body, which includes a floating logo and rows enclosed in a container-fluid. While everything looks great in Chrome, I am facing alignment issues in Edge and Firefox. I have considered using absolute positioning ...

Styling images and text in CSS within a jQuery UI autocomplete widget

I am currently using an autocomplete widget that displays text along with images. The results I have right now are not meeting my requirements. I want to customize the appearance of my results so that the words 'test' and either 'Federico&a ...

The useState hook is failing to properly initialize with the provided props value

I am facing an issue with two components in my code. In the App component, I initialize a variable called chosenCount with zero and then set it to a different value (e.g., 56). However, when I click the set button, the Counter component is supposed to rece ...

How can we transfer the value stored in a checkbox tag to the array present in the state of the current component?

Currently, I am facing an issue with using checkboxes to capture values and pushing them into the state array of the current component. It seems that only one value is being pushed into the array, and I'm unable to identify the root cause of this beha ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Is there a way to change the border property of an element when clicked, without causing the displacement of other elements?

I'm in the process of creating a webpage where users can choose the color and storage capacity of an item. Only one color/capacity can be selected at a time, and once chosen, it should be highlighted with a border. The issue I encountered is that whe ...

Issues with webpack-dev-server auto-refreshing the browser

I am having trouble with getting webpack-dev-server to automatically refresh the browser. Every time I make a change, I need to terminate it in the command line and restart before the browser shows the updated content. This is my configuration for webpack: ...

How to Resolve File Paths in CSS Using Angular 7 CLI

My assets folder contains an image named toolbar-bg.svg, and I am attempting to use it as the background image for an element. When I use background: url('assets/toolbar-bg.svg'), the build fails because postcss is unable to resolve the file. How ...

Swapping icons in a foreach loop with Bootstrap 4: What's the most effective approach?

I need a way to switch the icons fa fa-plus with fa fa-minus individually while using collapse in my code, without having all of the icons toggle at once within a foreach loop. Check out a demonstration of my code below: <link rel="stylesheet" href= ...

Having trouble displaying HTML UL content conditionally in Reactjs?

My goal is to display a list of items, limited to a maximum of 5 items, with a "more" button that appears conditionally based on the number of items in the list. However, I am encountering an issue where passing in 5 li items causes them to be rendered as ...