I have a 2d array of integers, each of which are being mapped to a render method that displays each value as a button. What I am trying to do is when the user clicks on the button, it updates the index of the elements, so it will show the updated value when the button is being rendered. However, the onClick method is never being called.
class Matrix extends Component {
state = {
rows: 0,
cols: 0,
elements: null
};
constructor() {
super();
this.state.elements = this.createMatrix();
}
updateElements = (i, j) => {
console.log("CLICK");
const newElements = this.state.elements.slice();
newElements[i][j]++;
this.setState({ elements: newElements });
console.log(this.state.elements[i][j]);
};
render() {
return (
<div>
<table>
<tbody>
{Object(
this.state.elements.map((e, i) => {
return (
<tr>
{Object(
e.map((f, j) => {
return (
<td>
<MatrixElement
onClick={() => this.updateElements(i, j)}
value={f}
/>
</td>
);
})
)}
</tr>
);
})
)}
</tbody>
</table>
</div>
);
}
createMatrix = () => {
var matrix = [];
var i, j;
var sub;
for (i = 0; i < this.state.rows; i++) {
sub = [];
for (j = 0; j < this.state.cols; j++) {
sub[j] = 0;
}
matrix[i] = sub;
}
return matrix;
};
}
class MatrixElement extends Component {
render() {
return <button>{this.props.value}</button>;
}
}
If I change the onClick method to this:
onClick={this.updateElements(i, j)}
I get overflow errors. I imagine there is a much simpler way to implement what it is I'm trying to do, but I don't understand why this doesn't work.