Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setState from a React material UI MenuItem click event

I am trying to change state based on a dropdown selection using Material UI.

The issue is the code below (stripped down) returns the list item, so I do not know what to do next.

RETURNED from the console.log(event.target) in the handleClose method

<li tabindex="0" class="MuiButtonBase-root-23 MuiListItem-root-72 MuiListItem-default-75 MuiListItem-gutters-79 MuiListItem-button-80 MuiMenuItem-root-70" role="menuitem">

The stripped down component:

campaigns gets populated from an api call. Thanks for any thoughts.

import React, { Component } from "react";
import Button from "@material-ui/core/Button";
import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";

class ABC extends Component {
  constructor(props) {
    super(props);
    this.state = {
      campaigns: [],
      anchorEl: null
    };

    this.handleClick = this.handleClick.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  // For the dropdown
  handleClick = event => {
    this.setState({ anchorEl: event.currentTarget });
  };

  handleClose = event => {
    this.setState({ anchorEl: null });
    console.log(event.target);
  };

  render() {
    const { campaigns, anchorEl } = this.state;

    return (
      <div>
        <Button
          aria-owns={anchorEl ? "simple-menu" : null}
          aria-haspopup="true"
          onClick={this.handleClick}
        >
          CHOOSE CAMPAIGN
        </Button>
        <Menu
          id="simple-menu"
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={this.handleClose}
        >
          {campaigns.map(item => (
            <MenuItem key={item.Id} onClick={event => this.handleClose(event)}>
              {item.Name}
            </MenuItem>
          ))}
        </Menu>

        {JSON.stringify(this.state.value)}
      </div>
    );
  }
}
like image 986
ivan7707 Avatar asked Jul 10 '18 21:07

ivan7707


1 Answers

Update MenuItem as :

<MenuItem key={item.Id} onClick={(event) => this.handleClose(item, event)}>{item.Name}</MenuItem>

This way you'll get that particular item as the event handler's parameter. Also I notice that the same function is passed as the onClose handler for Menu component which looked confusing. That might cause issue if Menu fires onClose event with a different parameter.

like image 114
Easwar Avatar answered Nov 15 '22 12:11

Easwar