Today I Learn/React

[React]배열 반복문 map

단추언니 2021. 10. 26. 12:38
반응형

리액트에서 반복문을 사용하려고 할 때 아래와 같이 return문 안에서 for 문은 사용할 수 없다

// for문 사용불가
function App() {
  const Month = ["1월", "2월", "3월", "4월", "5월", "6월"];
  return
    (
      <div>
        {
          for ( let i = 0; i < Month.length; i++) 
            {
              <span>{Month(i)}</span>
            }
        }
      </div>
    )
}

따라서 map 메소드를 사용하여 반복문을 실행한다

// map 메소드 사용하기
function App() {
  const Month = ["1월", "2월", "3월", "4월", "5월", "6월"];

  return (
    <div>
      {Month.map((month, index) => (
        <span key={index}> {month} </span>
      ))}
    </div>
  );
}
반응형