Open In App

Adding New Options In Dropdown Dynamically Using ReactJS

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

In many web applications, dropdowns are essential for selecting predefined options. However, there are times when you may need to allow users to add new options dynamically to the dropdown. This is especially useful in cases where the predefined options are not exhaustive or the user input is unpredictable.

In this article, we will walk through the process of adding new options dynamically to a dropdown in ReactJS.

Steps To Add New Options In Dropdown Dynamically Using ReactJS

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

npx create-react-app foldername
cd foldername

Step 3: 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,
{ createFilterOptions } from '@material-ui/lab/Autocomplete';
const filter = createFilterOptions();

const App = () => {

    // Our sample dropdown options
    const options = ['One', 'Two', 'Three', 'Four']

    return (
        <div style={{ marginLeft: '40%', marginTop: '60px' }}>
            <h3>Greetings from GeeksforGeeks!</h3>
            <Autocomplete
                filterOptions={(options, params) => {
                    const filtered = filter(options, params);
                    // Suggest the creation of a new value
                    if (params.inputValue !== '') {
                        filtered.push(`Add "${params.inputValue}"`);
                    }
                    return filtered;
                }}
                selectOnFocus
                clearOnBlur
                handleHomeEndKeys
                options={options}
                renderOption={(option) => option}
                style={{ width: 300 }}
                freeSolo
                renderInput={(params) => (
                    <TextField {...params} label="Enter Something"
                        variant="outlined" />
                )}
            />
        </div>
    );
}

export default App


Run the application using the following command from the root directory of the project:

npm start

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


Now if we start typing any other text apart from these options, it will show the Add feature to add our user typed option as shown above.



Next Article

Similar Reads