[react] Tic-Tac-Toe 개선사항 2번

ChanSol Jeong·2023년 8월 20일

react

목록 보기
9/13
post-thumbnail

Tic-Tac-Toe 개선사항 2번에 대하여
2.Rewrite Board to use two loops to make the squares instead of hardcoding them.

const drawBoard = new Array(9).fill(null).map((v, i) => i).reduce((result, value, index) => {
    if (index % 3 === 0) {
      result.push([value]);
    } else {
      result[Math.floor(index / 3)].push(value);
    }
    return result;
  }, []).map((v, i) => {
    return (<div className="board-row" key={i}>
      {v.map((v2,i2)=>{return <Square value={squares[v2]} onSquareClick={() => handleClick(v2)}></Square>})}
    </div>)
  })

하드코딩된 부분을 drawBoard 함수를 통하여 렌더링 되도록 수정하였다.
new Array(9).fill(null).map((v, i) => i)를 이용하여 [0,1,2,3,4,5,6,7,8]에 해당하는 배열을 만들어주고
reduce를 이용하여 3x3 크기의 이차원 배열을 만들어 준 뒤에
map을 이중반복문처럼 이용하여 JSX로 바꿔주었다.

vue는 직접적으로 <template>에서 html태그를 v-for를 이용하여 반복문을 작성할 수 있었기 때문에 map을 이용하여 JSX를 그려주는 과정이 되게 생소하였고 현재까지 react를 배우면서 vue와 가장 다르게 느껴지는 부분인 것 같다.

profile
Compostion API 맛있다!

0개의 댓글