본문 바로가기
Front/React

[React] List 와 Key 를 사용하여 출석부 출력하기

by 오엥?은 2023. 4. 20.
반응형

 

  • src > chapter_10 > AttendanceBook.jsx
import React from "react";

const students = [
    {
        name: "Yeeun"
    },
    {
        name: "Heongmin"
    },
    {
        name: "Hyungyu"
    },
    {
        name: "Kangin"
    },
];

function AttendanceBook(props) {
    return (
        <ul>
            {students.map((student) => {
                return <li>{student.name}</li>;
            })}
        </ul>
    );
}
export default AttendanceBook;

 

  • index.js 수정

위와 같이 잘 출력된다.

근데 콘솔창은 난리났다. key 값을 안 줘서 그렇다.

 

import React from "react";

const students = [
    {
        id : 1,
        name: "Yeeun"
    },
    {
        id : 2,
        name: "Heongmin"
    },
    {
        id : 3,
        name: "Hyungyu"
    },
    {
        id : 4,
        name: "Kangin"
    },
];

function AttendanceBook(props) {
    return (
        <ul>
            {students.map((student) => {
                return <li key={student.id}>{student.name}</li>;
            })}
        </ul>
    );
}
export default AttendanceBook;

배열에 id 를 추가하고, key 값을 설정한다.

이렇게 하면 더이상 콘솔창에 경고가 안 뜬다.

반응형