How can I dynamically display Material-UI's <MenuItem/> within a <DropDownMenu/> using ReactJS?

In my ReactJS + Material-UI project, I am working with an array named colors that contains different color strings such as "white", "blue", and "green. My goal is to render each color string as a <MenuItem/> within a <DropDownMenu/> component (http://www.material-ui.com/#/components/dropdown-menu). When a user selects a color from the dropdown menu, I want to log that specific color to the console (e.g., if "white" is chosen, then console.log("white")).

I tried using .forEach method but the dropdown menu does not display any strings and remains empty. What could be causing this issue?

Here is an excerpt of the code:

  constructor() {
    super()

    this.state = {
      value: 1,
    }
  }

  dropDownColorChange(event, index, value) {
    this.setState({value: value})
    //I need help on dynamically implementing this section based on array size. The goal is to console.log the color string of the selected item
  }

  render() {
    var colors = ["white", "blue", "green"]; //able to accommodate arrays of any size


    return (
             <div>
               <DropDownMenu
                value={this.state.valueTwo}
                onChange={this.dropDownColorChange}
              >
                {
                    <MenuItem value={1} primaryText="Select" />
                  colors.forEach(color => {
                    <MenuItem primaryText={color}/>
                  })
                }
              </DropDownMenu>
             </div>
    )
  }

Thank you for your assistance.

Answer №1

You're almost there! Make sure to utilize the map function to loop through available colors and create a MenuItem for each color:

const colors = ['white', 'blue', 'green'];

class ColorChanger extends Component {
  constructor() {
    super();

    this.state = {
      selectedColorValue: 1,
    };
  }

  handleColorChange(event, index, value) {
    console.log(`You have selected ${colors[value]} color`);

    this.setState({
      selectedColorValue: value
    });
  }

  render() {
    return (
      <div>
        <DropDownMenu value={this.state.selectedColorValue} onChange={this.handleColorChange}>
          {colors.map((color, index) =>
            <MenuItem key={index} value={index} primaryText={color} />
          )}
        </DropDownMenu>
      </div>
    );
  }
}

map (as opposed to forEach) creates an array with elements returned by the provided function. In your scenario, it returns a <MenuItem />.

Answer №2

Implementing the react hook allowed me to dynamically set the menu items when the menu icon is clicked, as well as passing a specific value to my action method.

const [menuItems, setMenuItems] = React.useState<IMenuItem[]>();
const [menuValue, setMenuValue] = React.useState<IMenuValue>();

const handleClickMenu = (
    event: React.MouseEvent<HTMLElement>,
    value: IMenuValue,
  ) => {
    setMenuItems(value.menuItems);
    setMenuTransaction(value);

    setMenuAnchorEl(event.currentTarget);
  };


return (

// ... modified code ...
<PositionedVertMenu
 data-testid={`menu`}
 open={Boolean(menuAnchorEl)}
 anchorEl={menuAnchorEl}
 onClick={(event: React.MouseEvent<HTMLElement>) => handleClickMenu(event, value)}
 onClose={handleCloseMenu}
>
  {menuValue &&
   menuItems?.map((option, menuIndex) => (
    <MenuItem
     data-testid={`menu-item-${menuIndex}`}
     onClick={() => option.action(menuValue, handleCloseMenu)}
    >
     <Typography>{translate(option.text)}</Typography>
    </MenuItem>
   ))}
 </PositionedVertMenu>
)



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

Basic progress bar

I'm attempting to create a basic download bar, but it's only displaying as a solid color without any transition animation. Furthermore, the "repeating-linear-gradient" feature isn't functioning and I'm struggling to figure out why. I&a ...

Is it possible to utilize the default error handling page rather than a specific view for expressing

Currently, I'm going through a tutorial on MDN Express for building a "Local Library" application that utilizes Pug (Jade) as its templating engine. In this segment of the tutorial, it explains the process of creating a controller to manage a form POS ...

Leveraging JavaScript event handlers within a progress wizard located within an update panel

I need assistance with implementing a password strength meter for a textbox within a wizard control. The issue I'm facing is that the password box does not become visible until step 4, preventing me from registering an event handler onload(). Placing ...

The component triggering the redirect prematurely, interrupting the completion of useEffect

I set up a useEffect to fetch data from an endpoint, and based on the response, I want to decide whether to display my component or redirect to another page. The problem I'm facing is that the code continues to run before my useEffect completes, lead ...

I keep encountering an issue with getJson

A snippet of my JavaScript code retrieves a JSON object from a URL. Here is the portion of the code in question: <script> $(document).ready(function(){ $("button").click(function(){ $.getJSON('url_address', {}, function(data) { ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

The Bootstrap modal causes the scrollbar to vanish upon closure

Despite trying numerous solutions and hacks on this issue from StackOverflow, none of them seem to work for me. Currently, I am utilizing a modal for the login process in Meteor (e.g. using Facebook login service) which triggers a callback upon successful ...

What information should be stored in the React state management system?

When working with React, state serves as a tool for storing data such as API responses and managing flags. But can we utilize the state for storing information that changes due to events or user actions but isn't displayed on the UI nor needs renderin ...

Establishing the state using the data from a React date and time component

Help needed! I'm encountering an issue with a reactDateTime component. I am struggling to retrieve the selected date value and store it in a state along with other form field attributes. Below is my code snippet: Datetime Component <Datetime ...

How can you determine when the onStateChange event in a Mui data grid is not occurring while in a loading state?

Every time the state changes in the mui data grid, the method onStateChange is triggered multiple times, usually around 6 or more times while the page is loading. To address this issue, I have implemented a temporary solution as follows: <DataGrid ...

Unable to click, but can only be activated by touchstart or mousedown

Is it possible to bind a 'click' event to a paragraph? Here is the function I am using: $(document).on('touchstart mousedown',"p span.text", function(e) { console.log('I was clicked'); *more code here* }); When I ...

Is there a way to ensure consistent heights for various elements within a column, even if their heights are

Currently, I am utilizing the flex property to create uniform columns and vh to ensure they have the same height. This setup is functioning properly, but within each column, there could be a varying number of items. I am interested in having the elements w ...

How can I store an access token received from the backend (in JSON format) in local storage and use it to log in?

My goal is to create a login interface using Plain Javascript. I have obtained a Token from the backend and now need assistance in utilizing this Token for the login process and storing it in LocalStorage. Although I have successfully made the API call, I ...

The 'data' variable is not defined in the React custom hook Pagination

I am currently working with an API that shows music categories on a browser, and I'm attempting to create a custom pagination hook. However, I keep encountering an error stating "object is not iterable." I am new to custom hooks and would appreciate a ...

Instructions for sending an email through a form while displaying a pop-up message

My Objective To create a functionality on my website where users can input their email addresses in a form and receive a validation popup indicating whether the email is valid or not. Background Information I am currently working on a website that allow ...

Issue with RequireJS: The data-main attribute fails to load the specified file

As I convert my small project into nodejs, I am facing an issue with the requireJS file that defines the JS to be used in the project not loading properly. Below is the structure of my project: https://i.sstatic.net/oYnqn.png The ng-app specifies the fr ...

How can you retrieve the value of a deleted option in React Material-UI Autocomplete component?

Having trouble retrieving the value of a deleted option when using an Autocomplete multiple select element? You're not alone. I attempted to use ChipProps = {{onDelete: some function}}, but unfortunately, it didn't work as expected. Instead of ge ...

Tips for referencing Google Maps initialization in individual files within a website application

After setting up my Google Maps API snippet: <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script> in the index.html file, I encountered the error: Uncaught InvalidValueEr ...

In the React environment, what occurs when two components both import the identical CSS file?

Consider the scenario where I have two unique React components: import { React } from "react"; import "./styles.css"; function ComponentX() { ... } export default ComponentX; import { React } from "react"; import "./ ...