How to Create More Options in ReactJS ?
More Options in React JS is a common feature that every application has to show the user some extra functionality on clicking on that button. Material UI for React has this component available for us and it is very easy to integrate.
Prerequisites:
Approach:
To create more options in React JS we will install the React Material UI packages. We will use the MoreVert and Menu components to display an options menu and show the dummy menu items using the MenuItem component.
Steps to Create React Application And Installing Module.
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm i @material-ui/core @material-ui/icons
Project Structure:
The updated dependencies in package.json file.
"dependencies": {
"@material-ui/core": "^4.12.4",
"@material-ui/icons": "^4.11.3",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example: This example implements more options menu using the Material UI MoreVert and Menu Compoents.
Javascript
// Filaname - App.js import React from "react" ; import MoreVertIcon from "@material-ui/icons/MoreVert" ; import IconButton from "@material-ui/core/IconButton" ; import MenuItem from "@material-ui/core/MenuItem" ; import Menu from "@material-ui/core/Menu" ; const App = () => { const [anchorEl, setAnchorEl] = React.useState( null ); const MyOptions = [ "Share via Whatsapp" , "Send Email" , "Download" , "Save as PDF" , ]; const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const open = Boolean(anchorEl); const handleClose = () => { setAnchorEl( null ); }; return ( <div style={{ marginLeft: "40%" , }} > <h2>How to Create More Options in ReactJS?</h2> <span>{ "More Options =>" } </span> <IconButton aria-label= "more" onClick={handleClick} aria-haspopup= "true" aria-controls= "long-menu" > <MoreVertIcon /> </IconButton> <Menu anchorEl={anchorEl} keepMounted onClose={handleClose} open={open} > {MyOptions.map((option) => ( <MenuItem key={option} onClick={handleClose} > {option} </MenuItem> ))} </Menu> </div> ); }; export default App; |
Step to Run Application: 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.
Contact Us