Greed94
Greed94

Reputation: 178

Components aren't rendered from mapping state

I want to map through "board" and create "Cell" components in adequate numbers as "board" is long.

Here's code:

function Grid({ player }) {
  const [board, boardSet] = useState([11, 2, 3]);
  const [cellsFill, cellsFillSet] = useState([
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 4, 8],
    [2, 4, 6],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
  ]);
  return (
    <section className="grid">
      {board &&
        board.map((el) => {
          return <Cell player={player} cellFillSet={boardSet}></Cell>;
        })}
    </section>
  );
}

When I try to console.log while mapping through "board" I get good numbers, but still 'Cell' doesn't appear.

PS: I now about adding key to list, for clearance it is deleted

EDIT: Problem is inside "Cell" component:

function Cell({ player, cellFillSet }) {
  const [filled, filledSet] = useState(null);
  const fill = async () => {
    turnSet((prev) => prev + 1);
  };
  useEffect(() => {
    cellFillSet(filled); //heres a problem, should be cellFillSet([filled])
  }, [filled]);
  return (
    <div className="cell" onClick={fill}>
      {filled}
    </div>
  );
}

Upvotes: 0

Views: 30

Answers (1)

Majid M.
Majid M.

Reputation: 4964

Try this :

 function Grid({ player }) {
  const [board, boardSet] = useState([11, 2, 3]);
  const createCellComponent = () =>
  { 
    if(board)
        return board.map((el) => {
            return <Cell player={player} cellFillSet={boardSet}></Cell>;
        })
  } 
  return (
    <section className="grid">
      {createCellComponent()}
    </section>
  );
}

Upvotes: 1

Related Questions