CONTEXT: I have this shape which is mainly built from 20×20 px MUI Boxes which are using a react component(Cell).Whenever a cell is clicked it’s state ( color ) is changed.
Problem : I tried creating a variable called count which gets incremented everytime a cell’s wrapper is clicked and lately display the total amount of red cells (clicked cells) inside a footer wrapper . Unfortunately it doesn’t seem to be working
Looking for : A way to count only one time each cell clicked and display it inside footer.
// =====================================================================================================================
// C O M P O N E N T
// =====================================================================================================================
class Cell extends React.Component {
state = {
color: '#bbdefb',
};
onChange = () => {
this.setState({color: 'red'});
};
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} onClick={handleCount}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
<Box sx={SX.secondrow} onClick={handleCount}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
<Box sx={SX.thirdrow} onClick={handleCount}>
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
<Cell />
</Box>
<Box sx={SX.forthrow} onClick={handleCount}>
<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
// -----------------------------------------------------------------------------------------------------------------
}
const handleCount = () => {
count++;
};
// =====================================================================================================================
// E X P O R T
// =====================================================================================================================
export default Main;
>Solution :
I assume the count variable is defined in the module scope. The render method didn’t execute again because you didn’t use this.setState(). This means your component didn’t re-render.
You should define count as a state of the Main component, and the render method will be executed when you call set new state:
class Main extends React.Component {
state = {count: 0}
handleCount = () => {
this.setState({ count: count+1 });
};
render() {
//...
}
}