Open In App

How To Disable Dropdown Options in ReactJS?

Last Updated : 07 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Dropdown menus are commonly used in web applications to allow users to select from a list of options. Sometimes, certain options need to be disabled based on specific conditions, such as availability, user permissions, or other logic. ReactJS makes it easy to manage dropdowns and disable options dynamically.

In this article, we will explore how to disable dropdown options in ReactJS.

Steps To Disable Dropdown Options in ReactJS

Step 1: Create a React application using the following command:

npx create-react-app foldername
cd foldername

Step 2: Install the material-ui modules using the following command:

npm install @material-ui/core
npm install material-ui/lab

Project Structure

Project Structure

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

JavaScript
//App.js

import React from 'react'
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';

const App = () => {

    // Sample options for dropdown
    const myOptions = ['One', 'Two', 'Three', 'Four', 'Five'];

    return (
        <div style={{ marginLeft: '40%', marginTop: '60px' }}>
            <h3>Greetings from GeeksforGeeks!</h3>
            <Autocomplete
                style={{ width: 400 }}
                options={myOptions}
                getOptionDisabled={(option) => {
                    // Mention options which needs to be disable
                    return option === myOptions[1] || option === myOptions[3]
                }}
                renderInput={(params) => (
                    <TextField {...params} label="Disabled options"
                        variant="outlined" />
                )}
            />
        </div>
    );
}

export default App


Explanation: This React component renders an autocomplete dropdown using Material-UI’s Autocomplete and TextField components. It provides a list of options (myOptions), and disables specific options (‘Two’ and ‘Four’) by using the getOptionDisabled function based on the condition provided.

Run the application using the following command:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Disable Dropdown Options in ReactJS



Next Article

Similar Reads