Development/React.js

[React] 배열 렌더링 하기

moretz0921 2022. 1. 4. 00:15

 

 

 

 

 

동적인 배열을 렌더링해야 할 때에는 자바스크립트 배열의 내장함수 map()을 사용한다.

map() 함수는 배열안에 있는 각 원소를 변환하여 새로운 배열을 만들어준다.

리엑트에서 동적인 배열을 렌더링해야 할 때는 이 함수를 사용하여 일반 데이터 배열을 리엑트 엘리먼트로 이루어진 배열로 변환해주면 된다. 

 

 

import React from 'react';

function User({ user }) {
  return (
    <div>
      <b>{user.username}</b> <span>({user.email})</span>
    </div>
  );
}

function UserList() {
  const users = [
    {
      id: 1,
      username: 'velopert',
      email: 'public.velopert@gmail.com'
    },
    {
      id: 2,
      username: 'tester',
      email: 'tester@example.com'
    },
    {
      id: 3,
      username: 'liz',
      email: 'liz@example.com'
    }
  ];

  return (
    <div>
      {users.map(user => (
        <User user={user} key={user.id} />
      ))}
    </div>
  );
}

export default UserList;

 

- key 값 중 id 인 고유한 값이 없다면 index를 넣어준다.

 

<div>
  {users.map((user, index) => (
    <User user={user} key={index} />
  ))}
</div>