오늘 배워 볼 것은 React에서 List를 Rendering하는 것입니다 !
오늘 만들 구조는
1. App.js에서 DairyList Component에 props로 dummyList를 넘겨줍니다.
2. dummyList를 props로 전달 받은 DairyList에서 DairyItem Component에 props로 넘겨받은 props를 그대로 넘겨줍니다.
3. dummyList를 props로 전달받은 DairyItem에서 리스트를 활용해 화면에 출력합니다.
1. App Component
1. 리스트를 props로 넘겨 줄 때, <DairyList dairyList={dummyList} /> 이런 식으로 변수를 넘겨주듯이 넘겨줍니다.
이 prop는 변경할 수 없습니다.
import "./App.scss";
import DairyList from "./DairyList";
const dummyList = [
{
id: 1,
author: "박규성",
content: "하이 1",
emotion: 5,
created_date: new Date().getTime(),
// 현재 시간을 숫자(millisecond)로 변환하여 저장
// new ; 생성자
...
];
function App() {
return (
<div className="App">
<DairyList dairyList={dummyList} />
</div>
);
}
export default App;
2. DairyList Component
1. DairyItem Component에게 넘겨받은 App으로부터 props를 넘겨주어야 합니다.
2. 한 개씩 넘겨주기 위해 map을 사용하였고, dairyList의 요소들을 it으로 받았습니다.
<div> {dairyList.map((it) => (<DairyItem key={it.id} {...it} />))} </div>
3. App으로부터 전달받은 props인 dailyList가 undefined인 상황을 고려해, 기본값을 []로 설정해두었습니다.
DairyItem.defaultProps={diaryLst:[ ]}
import React from "react";
import DairyItem from "./DairyItem";
const DairyList = ({ dairyList }) => {
return (
<div className="DairyList">
<h2>일기 리스트</h2>
<h4>{dairyList.length}개의 일기가 있습니다.</h4>
<div>
{dairyList.map((it) => (
<DairyItem key={it.id} {...it} />
))}
</div>
</div>
);
};
// undifined로 전달이 되면 오류가 뜨기에 기본값 설정해둠
DairyItem.defaultProps = {
dairyList: [],
};
export default DairyList;
3. DairyItem
1. DariyList로부터 전달받은 props들(...it) ; author, content, create_date,emotion,id를 인수로 전달하였습니다.
2. 전달받은 props들을 { }중괄호로 감싸 표현하였습니다.
import React from "react";
const DairyItem = ({ author, content, created_date, emotion, id }) => {
return (
<div className="DairyItem">
<div className="info">
<span>
작성자 : {author} | 감정 점수 : {emotion}{" "}
</span>
<br />
<span className="date">{new Date(created_date).toLocaleString()}</span>
</div>
<div className="content">{content}</div>
</div>
);
};
export default DairyItem;
만든 일기리스트는 아래와 같습니다.
'WebProgramming > React' 카테고리의 다른 글
[React] 라우팅(react-router-dom)(useParams, Query) (0) | 2022.07.07 |
---|---|
[React] Hook (0) | 2022.07.07 |
[React] 부모 Component -> 자식 Component에게 함수/리스 전달하기 (0) | 2022.07.04 |
[React] 자식 Component -> 부모 Component로 데이터 전달하기 (0) | 2022.07.04 |
[React] useRef를 이용한 DOM조작 (0) | 2022.07.03 |
[React] React 프로젝트 - DiaryEditor Component (0) | 2022.07.01 |
[React] Props (0) | 2022.07.01 |
[React] useState를 이요한 상태 관리 (0) | 2022.07.01 |