Using MUI Boxes i am trying to display a counter variable which gets incremented everytime one of these cells is clicked.I tried adding a counter as a state of a cell which gets incremented whenever the color of each Cell component is changed (everytime a cell is clicked) but doesn't seem to be working.
// =====================================================================================================================
// C O M P O N E N T
// =====================================================================================================================
class Cell extends React.Component {
state = {
color: '#bbdefb',
count: 0,
};
onChange = () => {
this.setState({color: 'red'});
this.setState({count: count++});
};
render() {
return (
<div
style={{
backgroundColor: this.state.color,
width: 20,
height: 20,
opacity: '60%',
outlineStyle: 'solid',
outlineWidth: '1px',
outlineColor: '#1a237e',
}}
onClick={this.onChange}
/>
);
}
}
class Main extends React.PureComponent {
render() {
return (
<Box sx={SX.root}>
<Box sx={SX.page}>
<MathGrid sx={SX.math1} />
<Box sx={SX.firstrow}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
<Box sx={SX.secondrow}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
<Box sx={SX.thirdrow}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
<Box sx={SX.forthrow}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
</Box>
<Box sx={SX.header} />
<Box sx={SX.footer}>
<Box sx={SX.counter}>{count}</Box>
</Box>
</Box>
);
}
// -----------------------------------------------------------------------------------------------------------------
// I N T E R N A L
// -----------------------------------------------------------------------------------------------------------------
}
// =====================================================================================================================
// E X P O R T
// =====================================================================================================================
export default Main;
4 things :
Try cell like this and see the comportement with comment different setState :
class Cell extends React.Component {
state = {
color: "#bbdefb",
count: 0,
};
onChange = () => {
this.setState({ color: "red" });
this.setState({ count: this.state.count++ });
// this.setState({ color: "red", count: this.state.count + 1 });
};
render() {
return (
<div
style={{
backgroundColor: this.state.color,
width: 20,
height: 20,
opacity: "60%",
outlineStyle: "solid",
outlineWidth: "1px",
outlineColor: "#1a237e",
}}
onClick={this.onChange}
>
{this.state.count}
</div>
);
}
}