I do not understand the following behavior:
I have written a component which should basically act as a menu. I am using MaterialUI for this. When a button in the menu is clicked, it should be set as "active" and visually represent this. For this the "selected" value is set to true.
If the button is clicked now, the state changes, but the list is not rendered again. What am I doing wrong? Or am I going a fundamentally wrong way to achieve my goal?
import * as React from 'react';
import {List, ListItemButton, ListItemText } from '@mui/material';
import { ListItem } from '@mui/material';
class Sidemenu extends React.Component {
menu = [];
constructor(props) {
super(props);
this.state = {
active: 'home'
}
}
changeActiveItem = (element) => {
this.setState({ active: element });
this.render();
}
buildMenu(active) {
console.log(active);
var buildMenu = ['home', 'stammdaten'];
for (let index = 0; index < buildMenu.length; index++) {
const element = buildMenu[index];
this.menu.push(
<ListItem key={element}>
<ListItemButton divider selected={element == active ? true : false} onClick={() => {
this.changeActiveItem(element);
console.log(this.state);
}}>
<ListItemText>{element}</ListItemText>
</ListItemButton>
</ListItem>
)
}
}
render() {
this.buildMenu(this.state.active);
return (
<List>
{this.menu}
{this.state.active}
{/* {this.menu} */}
</List>
)
}
}
export default Sidemenu;