Skip to content
Advertisement

React How to re render map function on change of variabel?

Here is an excerpt which should show my problem. In my project I do something with the grid and now I want to reset it, but I dont know how it works because if I change the grid variable, the .map() function doesnt re render. I hope you understand my problem and you can help me.

That is my code:

  export default function App() {
  const getInitialGrid = () => {
    const grid = [];
    for (let row = 0; row < 20; row++) {
      const currentRow = [];
      for (let col = 0; col < 50; col++) {
        currentRow.push([]);
      }
      grid.push(currentRow);
    }
    return grid;
  };
  const grid = getInitialGrid();
  return (
    <div className="App">
      {grid.map(function (row, rowIdx) {
        return (
          <div className="grid-row" key={rowIdx}>
            {row.map(function (node, colIdx) {
              return <div className="node">hi</div>;
            })}
          </div>
        );
      })}
    </div>
  );
}

Its the same code like here.

Thanks a lot!

Advertisement

Answer

You should use useState hook for that.

import React, { useState } from 'react';

export default function App() {
    // App code
    const [grid, setGrid] = useState(getInitialGrid());
    // more App code

then if you want to assign a new value to the grid and cause a rerender you do it like this (inside your App component):

setGrid(yourNewGrid);
Advertisement