What is the right way to use state in array mapping
I would like to mapping an array of data. On each item, I have a Menu and MenuItem from material-ui. I handle the method to open the Menu by changing the state. But, if I only use one state, then all the menu will opened because to open the menu on each array I only use this.state.open. Do you know how to make the Menu only open on the desire array? Thank you for any help.
here is what I've made so far.
import React, { Component } from 'react'
import Menu from '@material-ui/core/Menu'
import MenuItem from '@material-ui/core/MenuItem'
const dataMap = [
{
id: 1,
name: "john"
}, {
id: 2,
name: "Doe"
}
]
export default class MyComponent extends Component {
state = {
open: false
}
handleClick() {
this.setState({
open: !this.state.open
})
}
render() {
const mapResult = dataMap.map((item, index) => {
const id = item.id;
const name = item.name;
return <span key={index}>
{name}
<Menu
open={this.state.open}
>
<MenuItem id={id}>First</MenuItem>
<MenuItem id={id}>Second</MenuItem>
<MenuItem id={id}>Third</MenuItem>
</Menu>
</span>
})
return (
<div>
{mapResult}
</div>
)
}
}
Expected result: Only one Menu open at a time in the selected index.
You can use the data id as state instead of a boolean (eg. openedMenuId
)
import React, { Component } from 'react'
import Menu from '@material-ui/core/Menu'
import MenuItem from '@material-ui/core/MenuItem'
const dataMap = [
{
id: 1,
name: "john"
}, {
id: 2,
name: "Doe"
}
]
export default class MyComponent extends Component {
state = {
openedMenuId: null
}
handleClick(newOpenedMenuId) {
this.setState({
openedMenuId: newOpenedMenuId
})
}
render() {
const mapResult = dataMap.map((item, index) => {
const id = item.id;
const name = item.name;
return <span key={index}>
{name}
<Menu
open={this.state.openedMenuId === item.id}
>
<MenuItem id={id}>First</MenuItem>
<MenuItem id={id}>Second</MenuItem>
<MenuItem id={id}>Third</MenuItem>
</Menu>
</span>
})
return (
<div>
{mapResult}
</div>
)
}
}