Menu material UI component in React is not working when using class extended as Component

Viewed 890

I'm using React and material UI to build some menu elements.

If I use react component as function, if I click in the button, the menu is showed up as expected but if I use class extends Component it is not opening anymore.

    import React from 'react';
    import {Component } from 'react';
    import Button from "@bit/mui-org.material-ui.button";
    import Menu from "@bit/mui-org.material-ui.menu";
    import MenuItem from "@bit/mui-org.material-ui.menu-item";
    import Fade from "@bit/mui-org.material-ui.fade";

    class  FadeMenu extends Component {

        constructor(props){
            super(props)
            this.state = {
                anchorEl : null,
                open: false
            }
            this.setAnchorEl = this.setAnchorEl.bind(this)
            this.handleClick = this.handleClick.bind(this)
            this.handleClose = this.handleClose.bind(this)
        }
    handleClick(event) {
        this.setAnchorEl(event.currentTarget);
    }
        setAnchorEl(value){
            this.setState({
                anchorEl: value,
                open: !this.state.open
            })
        }
    handleClose() {
        this.setAnchorEl(null);
    }
    renderMenu(){
      return(
      <Menu id="fade-menu" anchorEl={this.state.anchorEl} open={this.state.open} onClose={this.handleClose} TransitionComponent={Fade}>
            <MenuItem onClick={this.handleClose}>Profile</MenuItem>
            <MenuItem onClick={this.handleClose}>My account</MenuItem>
            <MenuItem onClick={this.handleClose}>Logout</MenuItem>
        </Menu>
       )
    }
    render(){
    return (<div>
        <Button aria-owns={this.state.open ? 'fade-menu' : undefined} aria-haspopup="true" onClick={this.handleClick}>
            Open with fade transition
        </Button>
          {this.renderMenu}
        </div>)
        }

    }

    export default FadeMenu;
1 Answers

The issue is you are trying to render a function, not a component:

  {this.renderMenu}

Call the function to get the JSX from it, and it will work:

  {this.renderMenu()}
Related