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;
import * as React from 'react';
import { List, ListItemButton, ListItemText } from '@mui/material';
import { ListItem } from '@mui/material';
class Sidemenu extends React.Component {
constructor(props) {
super(props);
this.state = {
active: 'home'
}
}
changeActiveItem = (element) => {
this.setState({ active: element });
this.render();
}
buildMenu() {
var buildMenu = ['home', 'stammdaten'];
return buildMenu.map((element) => {
return (
<ListItem key={element}>
<ListItemButton divider selected={element == this.state.active ? true : false} onClick={() => {
this.changeActiveItem(element);
console.log(this.state);
}}>
<ListItemText>{element}</ListItemText>
</ListItemButton>
</ListItem>
)
})
}
render() {
return (
<List>
{this.buildMenu()}
{this.state.active}
</List>
)
}
}
export default Sidemenu;
I now understand what the problem is. React does update partially. In this example I pass a variable, respectively an object to the specific place in the code.
React now compares the state before and after the state change. Both before and after the update the same object is passed.
React does not detect any change and does not rerender the object.
The solution is to parse the object into a new one.
{this.menu}
have to be changed to:
[...{this.menu}]
so with every state change a new object is recognized. However, the whole thing is to be enjoyed with some caution, in my special case, it is to be assumed that with each state change also the place must be rendered again.