List
- Array 배열
- JavaScript의 변수나 객체들을 하나의 변수로 묶어 놓은 것
Key
- 각 객체나 아이템을 구분할 수 있는 고유한 값
- Key의 값은 같은 List에 있는 Elements 사이에서만 고유한 값이면 된다.
다음과 같이 같은 Element 사이에서의 고유한 값이면 된다.
여러개의 Component 렌더링 하기
- map() : 배열에 들어있는 각 변수에 처리를 한 뒤 리턴
- const doubled = numbers.map((number) => number * 2);
- 위는 numbers 배열의 각 변수를 2배로 한 뒤 리턴
numbers 배열에 잇는 값들로 map() 함수를 이용해 listItems 라는 컴포넌트 배열을 만든다. 그리고 ul 태그안에 넣고 렌더링한다.
그럼 다음과 같은 결과가 리턴될 것이다.
주의할 점!
- map() 함수 안에 있는 Elements는 꼭 key가 필요하다.
map() 함수를 이용할 때, 키값을 설정하지 않으면 다음과 같은 오류가 뜬다.
실습 : 출석부 출력하기
import React from "react";
const students = [
{
name: "Inje",
},
{
name: "Steve",
},
{
name: "Bill",
},
{
name: "Jeff",
},
];
// map() 함수 사용
function AttendanceBook(props) {
return (
<ul>
{students.map((student) => {
return <li>{student.name}</li>
})}
</ul>
);
}
export default AttendanceBook;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import AttendanceBook from './chapter_10/AttendanceBook';
ReactDOM.render(
<React.StrictMode>
<AttendanceBook />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
다음과 같이 map() 함수를 활용하여 student 배열에 있는 학생 이름들을 나열시켰다. 그런데, 문제는 map() 함수 사용 시, Key 값을 사용하지 않았기에 에러가 문구가 뜨는 것을 확인할 수 있다.
import React from "react";
const students = [
{
id: 1,
name: "Inje",
},
{
id: 2,
name: "Steve",
},
{
id: 3,
name: "Bill",
},
{
id: 4,
name: "Jeff",
},
];
// map() 함수 사용
function AttendanceBook(props) {
return (
<ul>
{students.map((student) => {
return <li key={student.id}>{student.name}</li>
})}
</ul>
);
}
export default AttendanceBook;
id 값을 설정 후, map() 함수에서 key 값으로 학생들의 고유 데이터를 가져온 뒤, 이름을 출력하였다. 이러면 콘솔창에서 에러가 뜨지 않는다.
<ul>
{students.map((student) => {
return <li key={`student-id-${student.id}`}>{student.name}</li>
})}
</ul>
포멧팅 된 문자열을 키로 사용하는 것 역시 가능하고
<ul>
{students.map((student, index) => {
return <li key={index}>{student.name}</li>
})}
</ul>
index를 사용하는 방법도 있으나 위에서 말한 것 처럼 권장하지 않는다.
'React' 카테고리의 다른 글
[React] Lifting State Up (0) | 2024.08.19 |
---|---|
[React] Form과 Controlled Component (0) | 2024.08.18 |
[React] Conditional Rendering (0) | 2024.08.12 |
[React] Event (0) | 2024.08.08 |
[React] Hooks 실습 (0) | 2024.08.07 |