공부한것/React
[React] 데이터 목록 출력하기.
flyda
2022. 7. 25. 17:53
1. 더미 데이터 추가
const DUMMY_DATA = [
{
id: 'm1',
title: 'This is a first meetup',
image:
'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Stadtbild_M%C3%BCnchen.jpg/2560px-Stadtbild_M%C3%BCnchen.jpg',
address: 'Meetupstreet 5, 12345 Meetup City',
description:
'This is a first, amazing meetup which you definitely should not miss. It will be a lot of fun!',
},
{
id: 'm2',
title: 'This is a second meetup',
image:
'https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Stadtbild_M%C3%BCnchen.jpg/2560px-Stadtbild_M%C3%BCnchen.jpg',
address: 'Meetupstreet 5, 12345 Meetup City',
description:
'This is a first, amazing meetup which you definitely should not miss. It will be a lot of fun!',
},
];
2. map 메서드 사용
컴포넌트에서 더미 데이터를 map 메서드로 모든 요소에 접근해서 주어진 함수를 실행한다. map은 새로운 배열을 반환한다.
function AllMeetupPage() {
return <section>
<h1>All Meetups</h1>
{DUMMY_DATA.map((meetup)=> {
return <li key={meetup.id}>{meetup.title}</li>
})}
</section>
}
export default AllMeetupPage;
화살표 함수에서 meetup을 매개변수로 받아서 현재 요소에 접근할 수 있다.
만약 <li>에서 key 속성을 빼먹으면 다음과 같은 경고창이 나온다!!
index.js:1 Warning: Each child in a list should have a unique "key" prop.
key속성은 유일한 값을 지정해주어야 한다!! 지금은 각 요소에서 id값이 유일하기 때문에 id로 넣어주었다.