'How to implement dropdown menu in React JS using Material UI?

I have a dropdown which has a nested menu as shown below.

enter image description here

The dropdown upon expanding shows two options:

enter image description here

The problem is upon clicking any of the items the children options under Tenant Name or Dealer ID display for a second and disappear. How to solve this problem and next is how to store values which the user selects?

My code is as follows:

   export default class DropDownMenuSimpleExample extends React.Component {

 constructor(props) {
super(props);
this.state = {
  dropDownData: [
    {
      value: '',
      tenantName: '',
      dealerId: '',
    },
  ],
};
}

handleChange = (event, index, value) => {
    this.setState({ value });
    console.log(event, index, value);
 }

render() {
 return (

  <DropDownMenu
      style={styles.customWidth}
      anchorOrigin={{ horizontal: 'left', vertical: 'top' }}
      targetOrigin={{ horizontal: 'left', vertical: 'top' }}
      className={{ backgroundcolor: '#CFD8DC' }}

  >

    <MenuItem
        value={this.state.value}
        onChange={this.handleChange}
        primaryText="TENANT NAME"
        rightIcon={<ArrowDropRight />}
        menuItems={[
          <MenuItem value={100} primaryText="CA-CAR" />,
          <Divider />,
          <MenuItem value={101} primaryText="TEKION" />,
        ]}
    />

    <MenuItem
        value={this.state.value}
        onChange={this.handleChange}
        primaryText="DEALER ID"
        rightIcon={<ArrowDropRight />}
        menuItems={[
          <MenuItem value={1} primaryText="1" />,
          <MenuItem value={2} primaryText="2" />,
          <MenuItem value={3} primaryText="2" />,
          <MenuItem value={4} primaryText="4" />,
        ]}
    />
  </DropDownMenu>
  );
 }
}


Solution 1:[1]

to get values that user selects you need to bind a onChange event like

<SelectField  onChange={(evt,index,name) =>this.getOccasion(name) />

getOccasion()
{
this.setState({
//update to state
})
}

no idea why your list appears for a second.Check console and see if it shows any error.Still you can try to wrap your material ui components in

<MuiThemeProvider>

but think you have missed some loaders in webpack may be thats why the behaviour is unusual

Here is my webpack configuration see if it helps

const postcssPlugins = [
  require('postcss-cssnext')(),
  require('postcss-modules-values')
];

const scssLoader = [
  { loader: 'style-loader' },
  { loader: 'css-loader' },
  { loader: 'sass-loader' }
];

const postcssLoader = [
  { loader: 'style-loader' },
  { loader: 'css-loader', options: { modules: true } },
  { loader: 'postcss-loader', options: { plugins: () => [...postcssPlugins] } }
];

var path = require('path');

module.exports = {
          entry: './src/main/resources/static/js/app.js',
          output: {
            path: __dirname + '/src/main/resources/static/js', 
            filename: 'bundle.js' 
          },

  module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',

            query: {
               presets: ['es2015', 'react']
            }
         },
         {
             test: /\.(scss|sass)$/,
             loader: scssLoader,
             include: [__dirname]
           },
           { test: /\.css$/,
             loader: postcssLoader,
             include: [__dirname]
           }
      ]

   }
};

Solution 2:[2]

enter image description hereLets see the below source code, which help you to build more understanding:

Dropdown.js This is a Dropdown component class, which help us to render the dropdown menu content. When user click on the dropdown menu, then this component class render the updated dropdown menu list in browser.

showDropdownMenu : This method helps to display the dropdown menu content. hideDropdownMenu : This method helps to hide the dropdown menu content.

import React from 'react';
import './style.css';


class Dropdown extends React.Component {
constructor(){
 super();

 this.state = {
       displayMenu: false,
     };

  this.showDropdownMenu = this.showDropdownMenu.bind(this);
  this.hideDropdownMenu = this.hideDropdownMenu.bind(this);

};

showDropdownMenu(event) {
    event.preventDefault();
    this.setState({ displayMenu: true }, () => {
    document.addEventListener('click', this.hideDropdownMenu);
    });
  }

  hideDropdownMenu() {
    this.setState({ displayMenu: false }, () => {
      document.removeEventListener('click', this.hideDropdownMenu);
    });

  }

  render() {
    return (
        <div  className="dropdown" style = {{background:"red",width:"200px"}} >
         <div className="button" onClick={this.showDropdownMenu}> My Setting </div>

          { this.state.displayMenu ? (
          <ul>
         <li><a className="active" href="#Create Page">Create Page</a></li>
         <li><a href="#Manage Pages">Manage Pages</a></li>
         <li><a href="#Create Ads">Create Ads</a></li>
         <li><a href="#Manage Ads">Manage Ads</a></li>
         <li><a href="#Activity Logs">Activity Logs</a></li>
         <li><a href="#Setting">Setting</a></li>
         <li><a href="#Log Out">Log Out</a></li>
          </ul>
        ):
        (
          null
        )
        }

       </div>

    );
  }
}

export default Dropdown;

style.css This is a style sheet design for the drop-down menu.

 .dropdown {
     position: relative;
     display: inline-block;
}
 ul {
     list-style-type: none;
     margin: 0;
     padding: 0;
     top:45px;
     right:0px;
     width: 200px;
     background-color: white;
     font-weight:bold;
     position: absolute;

     box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
     z-index: 1;
}
 li a {
     color: #000;
     text-decoration: none;
}
 li {
     padding: 8px 16px;
     border-bottom: 1px solid #e5e5e5;
}
 li:last-child {
     border-bottom: none;
}
 li:hover {
     background-color: #e5e5e5;
     color: white;
}
 .button{
     width:178px;
     height:18px;
     background-color:#ff3232 ;
     padding:12px;
     border-radius:5px;
     font-weight:bold;
     color:white;
}
 .button:before{
     content:"";
     position:absolute;
     width:0px;
     height:0px;
     border: 10px solid;
     border-color: white transparent transparent transparent;
     right:6px;
     top:18px;

}

index.js This is a main component which helps to display the dropdown menu.

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import Dropdown from './dropdownmenu/Dropdown';


var displayDropdown = (
      <div style={{display: 'flex', justifyContent: 'center'}} >
        <Dropdown />
      </div>
      );

ReactDOM.render(displayDropdown, document.getElementById('root'));

registerServiceWorker();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vikram Saini
Solution 2