React - 반복되는 컴포넌트 (Map)

Jinwoo Ma·2023년 11월 14일

React

목록 보기
6/17
post-thumbnail

화면에 다음과 같이 반복되는 컴포넌트가 있다.

return (
    <div style={style}>
      <div style={squareStyle}>감자</div>
      <div style={squareStyle}>고구마</div>
      <div style={squareStyle}>오이</div>
      <div style={squareStyle}>가지</div>
      <div style={squareStyle}>옥수수</div>
    </div>
  );

이 컴포넌트들을 처리하기 위해 우리는 일일이 작성해 주었지만, 컴포넌트가 추가될 때마다 또 작성해야 한다는 불편함이 있다. 그래서 이번 포스팅에선 map을 활용해 중복을 없애는 방법에 대해 알아볼 예정이다.

const vegetables = ["감자", "고구마", "오이", "가지", "옥수수"];

  return (
    <div className="app-style">
      {vegetables.map((vegetableName) => {
        return (
          <div className="square-style" key={vegetableName}>
            {vegetableName}
          </div>
        );
      })}
    </div>
  );

vegetables라는 배열에 항목을 넣어주고, map을 활용해 div태그 속 vegetable 항목들로 이뤄진 배열을 만들어 주었다.

map() 은 배열의 모든 요소를 순회한다. 그래서 클라이언트에서는 배열 형태의 데이터를 활용해서 화면을 그려주는 경우가 많고, 이 때 배열의 값들로 동적으로 컴포넌트를 만들수 있다.

0개의 댓글