I am working through the Flavio Copes Pixel Art app in his React course and I'd like to add a button that can resize my "canvas". The canvas is a 2D array that is initialized like so:
const [matrix, setMatrix] = useState(
Array(size)
.fill()
.map(() => Array(size).fill(0)));
The size
variable is passed down as a prop from the parent component, which has a hook to manage the state from an input field. The matrix is used to render "Pixel" components (30px x 30px divs) by mapping through each row/col like so:
<div className={css(styles.canvas)}>
{matrix.map((row, rowIndex) =>
row.map((_, colIndex) => {
return (
<Pixel
key={`${rowIndex}-${colIndex}`}
background={Colors[matrix[rowIndex][colIndex]]}
onClick={() => changeColor(rowIndex, colIndex)}
/>
);
})
)}
</div>
I am able to update the width of the canvas (# of columns), but I think that the number of total Pixels remain constant and subsequent rows are added/subtracted that do not equal the number of columns. You can replicate the error by inputting a new value into "Canvas Size" and clicking "Resize Canvas" on my demo.
Why do the number of rows differ from the number of columns?
All of the code is available in my repo.