컴포넌트 중첩일 때 props 전달

박은정·2021년 8월 27일
0

프로젝트

목록 보기
9/34

대략적인 구조를 보면

main.js > Feeds.js > Comment.js 의 순서로 구성되어있는데
각각의 Feeds 및 Comment 는 컴포넌트이다

이러한 구조에서 Comment에 props를 전달하기 위해
나는 처음에 Feeds에 commentList 배열의 형태로 Comment컴포넌트에게 props를 전달해줘야 된다고 생각했지만

종택님의 조언으로는 Feeds에서 바로 전달하는 것이 아니라
Main 컴포넌트에서 Feeds 컴포넌트로 전달해줘야
Feeds 컴포넌트에서 commentList props를 전달받고
다시 Comment 컴포넌트로 전달할 수 있다고 하셨다

그래서 그런 조언을 받아 코드를 작성하면 아래와 같이 적을 수 있다

// main.js

const commentList = [
  {
    id: 1,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
  },
  {
    id: 2,
    userId: 'ryan.seoul.icon',
    commentText: '춘식이는 프렌즈를 좋아해',
  },
  {
    id: 3,
    userId: 'boragom_molly',
    commentText: '무더운 여름밤 춘식이와 나선 밤 산책',
  },
];

const feedsList = [
  {
    id: 4,
    feedsProfileUrl: './images/eunjungPark/feeds-profile.png',
    userId: 'eunJeong ',
    feedsImageUrl: './images/eunjungPark/feeds-image.png',
    mineProfileUrl: './images/eunjungPark/feeds-profile.png',
    likeUserId: 'chunSig ',
    likeUserNum: '10명',
    commentTitText: '수호가 라이언을 좋아하는구나..!',
    commentList,
  },
  {
    id: 5,
    feedsProfileUrl: './images/eunjungPark/feeds-profile.png',
    userId: 'eunJeong22 ',
    feedsImageUrl: './images/eunjungPark/feeds-image.png',
    mineProfileUrl: './images/eunjungPark/feeds-profile.png',
    likeUserId: 'chunSig22 ',
    likeUserNum: '20명',
    commentTitText: '수호가 라이언을 좋아하는구나..!',
    commentList,
  },
  {
    id: 6,
    feedsProfileUrl: './images/eunjungPark/feeds-profile.png',
    userId: 'eunJeong33 ',
    feedsImageUrl: './images/eunjungPark/feeds-image.png',
    mineProfileUrl: './images/eunjungPark/feeds-profile.png',
    likeUserId: 'chunSig33 ',
    likeUserNum: '30명',
    commentTitText: '수호가 라이언을 좋아하는구나..!',
    commentList,
  },
];
commentList,

이부분도 보면 원래는 commentList: commentList, 로 적어줘야 되는게 맞지만
ES6버전에서는 동일한 key value이면 하나로 축약해서 적을 수 있다

그리고 이러한 배열 형태인 props 를 Feeds 컴포넌트로 전달할 때에는
아래와 같이 적을 수 있다

<Feeds
    key={feed.id}
    feedsProfileText={feed.feedsProfileText}
    feedsProfileUrl={feed.feedsProfileUrl}
    userId={feed.userId}
    feedsImageText={feed.feedsImageText}
    feedsImageUrl={feed.feedsImageUrl}
    mineProfileText={feed.mineProfileText}
    mineProfileUrl={feed.mineProfileUrl}
    likeUserId={feed.likeUserId}
    likeUserNum={feed.likeUserNum}
    commentTitText={feed.commentTitText}
    commentList={feed.commentList} // 이부분!!!
  />

그래서 이렇게 받은 Feeds 컴포넌트에서 Comment 컴포넌트로 전달은 아래와 같이 할 수 있다

<Comment
    key={comment.id}
    userId={comment.userId}
    commentText={comment.commentText}/>

느낀점

너무 단순한 질문이라 거절당할 생각에 혼자 찾아보려고 했지만
남들은 다른과제에 집중할 때 나는 혼자 제자리 걸음하는 것같아
힘들면서도 스트레스는 많이 받아 힘들었다

어제 종택님께서 혼자 책이나 강의 보지말고 멘토님께 질문을 하라는 조언을 듣고
용기를 가지고 단순하지만... 질문을 했는데 거절당하지 않아서 기뻤다!

월요일부터는 프로젝트를 진행할 텐데 기업협업가기 전까지 찾아봐도 모를 것같을 때에는 혼날 각오를 하고... 여러 멘토님들께 질문하러 가야겠다!

위코드라서 가능한 것...!

profile
새로운 것을 도전하고 노력한다

0개의 댓글