Enhancing Settings Menu in SUSI Webchat using Material-UI Menu React Component

Material-UI is a great library for react developers since you can directly use the material components in your app. The SUSI.AI Webchat uses Material-UI (https://github.com/callemall/material-ui). In this blog we’ll see how a Menu component is implemented in settings page of susi’s web chat app.

Menu & MenuItem Component

Menu component allows you execute an action on selecting from a list. In the settings menu we want to change the state variable to which setting details is binded (ie. on change of state variable the setting details corresponding to selected menu changes).

A simple menu component is defined like this –

<Menu>
        <MenuItem primaryText="Item 1" />
        <MenuItem primaryText="Item 2" />
        <MenuItem primaryText="Item 3" />
        <MenuItem primaryText="Item 4" />
</Menu>

Menu component and MenuItem accepts some properties too. Like if you add disable={true} then the MenuItem it will disable onClick action of MenuItem.

Adding Icon

MenuItem can contain icons through defining leftIcon and rightIcon properties.

Example snippet:

<MenuItem primaryText="Download" leftIcon={<Download />} />

Output:

You can also add style to the leftIcon or rightIcon in style property of MenuItem.

Active State of MenuItem

You must be interested in assigning a different style to the active MenuItem in the Menu. This can be achieved through selectedMenuItemStyle property. It allows overriding the inline-style property of selected MenuItem.

To implement this we need to use the concept of ‘controlled component’. Each MenuItem has to be assigned a value. Also, assign the Menu with a state variable.

<Menu 
 selectedMenuItemStyle={{color: '#FFFFFF'} }   
 value={this.state.selectedItem} > 
    <MenuItem primaryText="Item 1" value='1'/> 
    <MenuItem primaryText="Item 2" value='2' /> 
</Menu>

This way the state variable will control Menu’s value and the selectedMenuItemStyle property will override the inline-style of the corresponding MenuItem.

Implement onClick function for MenuItem and change the state value.

This way you can add style to active MenuItem.

You can see the demo of how it was implemented in chat settings at https://chat.susi.ai/settings

Also, you can check out the github repo https://github.com/fossasia/chat.susi.ai

Note – Make sure that you define the state change function outside render else it will get a warning like this.

Warning: setState(…): Cannot update during an existing state transition (such as within `render` or another component’s constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

This will result in abnormal behaviour in runtime. So keep that mind in while creating the function to change the state.

Resources