0

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.

  • Can you please take a look at this post about how to deal with 2 dimensional array initialization ? https://stackoverflow.com/questions/18163234/declare-an-empty-two-dimensional-array-in-javascript – Arar Mar 30 '20 at 03:20
  • The 2D array needs to be initialized with every entry = 0, which is why I am using the fill().map() – Peter Arriaza Mar 31 '20 at 12:28

1 Answers1

0

I do not see change of columns/rows in your repo. This function should do the trick

const updateMatrixSize = (size) => {
  setMatrix(
    matrix.length > size
      ? matrix.slice(0, size).map(it => it.slice(0, size)))
      : [ 
         ...matrix.map(it => ([
                              ...it,
                              ...new Array(size - matrix.length).fill(0)
                             ])
         ),
         ...new Array(size - matrix.length).fill(0)
        ]
  )
}

PS you have a typo in your repo

props.setMsatrixState(newMatrix);
rockTheWorld
  • 481
  • 4
  • 10