오늘은 Component에서 Component로 배열을 전달한건데요 !
일단, 배열을 보낼 파일을 만들어보겠습니다.
emotion정보들이 담긴 배열을 전달 해 볼 것입니다.
# src > util > emotion.js
emotionList배열을 정의하여 export시켜주었습니다.
객체로 구성되엉 있으며, 각각의 객체는 id,img,descript로 작성되어있습니다.
export const emotionList = [
{
emotion_id: 1,
emotion_img: process.env.PUBLIC_URL + `/assets/emotion1.png`,
emotion_descript: "완전 좋음",
},
{
emotion_id: 2,
emotion_img: process.env.PUBLIC_URL + `/assets/emotion2.png`,
emotion_descript: "좋음",
},
{
emotion_id: 3,
emotion_img: process.env.PUBLIC_URL + `/assets/emotion3.png`,
emotion_descript: "그럭저럭",
},
{
emotion_id: 4,
emotion_img: process.env.PUBLIC_URL + `/assets/emotion4.png`,
emotion_descript: "나쁨",
},
{
emotion_id: 5,
emotion_img: process.env.PUBLIC_URL + `/assets/emotion5.png`,
emotion_descript: "끔찍함",
},
];
# src > pages > Diary.js
1 : util/emotion으로부터 emotionList를 가져옵니다.
6~8 : emotionList를 map을 통해 하나씩 꺼낸 후 it에 집어넣어, it.emotion_id === data.emotion인 것을 찾습니다.
이 때, parseInt를 통해 숫자형으로 변환시켜줍니다.
11 : data.emotion과 일치하는 id를 가져와 src속성에 전달해줍니다.
import { emotionList } from "../util/emotion";
const Diary = () => {
if (!data) {
return <div className="DiaryPage">로딩중입니다...</div>;
} else {
const curEmotionData = emotionList.find(
(it) => parseInt(it.emotion_id) === parseInt(data.emotion)
);
return (
<article>
<section>
<h4>오늘의 감정</h4>
<div className="diary_img_wrapper">
<img src={curEmotionData.emotion_img} />
</div>
</section>
</article>
</div>
);
}
'WebProgramming > React' 카테고리의 다른 글
[React] React로 로그인 기능 구현하기 (+ Firebase이용하여) (0) | 2022.08.31 |
---|---|
[React] fetch를 통해 HTTP 요청 보내기 (0) | 2022.08.02 |
[React] 메모이징 (React.memo, useCallback, useMemo) (0) | 2022.07.30 |
[React] Modal 작성하기 (0) | 2022.07.30 |
[React] useContext를 이용해 전역 props전달하기 2 (context.js로 분리시키기) (0) | 2022.07.22 |
[React] useEffect를 이용한 DOM조작 (0) | 2022.07.22 |
[React] useReducer를 이용한 상태관리 (0) | 2022.07.22 |
[React] useRef로 input 상태 관리하기 (0) | 2022.07.21 |