댓글 컴포넌트화

박은정·2021년 8월 26일
0

프로젝트

목록 보기
6/34
post-thumbnail
<span className="user-id">hoon-zz</span>
<span className="comment-text">은정아 라이언 좀 적당히 사</span>

이런식으로 반복되는 댓글 코드를 컴포넌트화 한다면 아래와 같이 작성할 수 있는데

// Comment.js
// React 안의 Component 를 import 하겠다
import React, {Component} from 'react';

class Comment extends Component {
    render() {
        return (
            <div>
                <span className="user-id">hoon-zz</span>
                <span className="comment-text">은정아 라이언 좀 적당히 사</span>
            </div>
        );
    }
}

export default Comment;
// Main.js
import React, { Component } from "react";
import Comment from "./Comment";

(중간생략...)

<Comment />
<Comment />
<Comment />

이렇게 적게 되면 동일한 Comment 컴포넌트가 반복되기만 하고
그 마저도 컴포넌트는 내가 복사해서 붙여넣어줘야 한다

그래서 Comment 컴포넌트에서 달라지는 내용인 userId, commentText를
Main → Comment 컴포넌트로 props를 통해 전달해주면 좋은데
그러한 props는 배열 안의 객체형태이다

따라서 Main에서 받은, Comment에서 사용할 props 를 넣을 Main 컴포넌트 외부에 commentList 라는 변수에 배열로 작성한다

const commentList = [
  {
    id: 1,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
  },
  {
    id: 2,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
  },
  {
    id: 3,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
  },
];

Comment 컴포넌트에 전달할 props를 점 연산자를 이용해 아래와 같이 전달한다

마치 html에서 비슷한 tag인데 attribute를 다르게 줘서
다른내용의 요소를 화면에 출력하는 과정같았다
tag → Component
attribute → props

<Comment
    userId={tcommentList[0].userId}
    commentText={commentList[0].commentText}/>
<Comment
    userId={tcommentList[1].userId}
    commentText={commentList[1].commentText}/>
<Comment
    userId={tcommentList[2].userId}
    commentText={commentList[2].commentText}/>

지금도 보면 commentList[0] 을 제외하고 (이 값은 배열 commentList의 객체형태의 요소이다)
컴포넌트를 반복적으로 적어줘야 되는데 이런 방식은 비효율적이기 때문에
map()함수를 이용해서 인자로 받은 commentList에 담긴 props 배열에
일정한 작업 을 해주고 새로운 배열로 반환해준다

그러한 일정한 작업 은 Comment 컴포넌트에 prop를 정해주는 것이다
그리고 map() 함수는 자바스크립트 문법이기 때문에 중괄호로 한 번 묶어 줄 것이다

{commentList.map(comment => {
  return (
    <Comment
      userId={comment.userId}
      commentText={comment.commentText}
    />
  );
})}

이 코드를 보면 기존의 commentList 배열에서 요소 하나하나를 comment라고 지정하고

// 첫번째 comment가 가리키는 것
{
    id: 1,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
}
// 두번째 comment가 가리키는 것
{
    id: 2,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
}
// 세번째 comment가 가리키는 것
{
    id: 3,
    userId: 'hoon-zz',
    commentText: '은정아 라이언좀 그만 사',
}

map()함수는 각각의 요소에 따라 실행만 하고 따로 반환은 안하기 때문에
return 키워드를 통해 새로운 배열로 반환이 된다

그리고 반환될 값으로는 Comment 컴포넌트에
각각 userId, commentText 라는 props의 묶음인 배열이다

사실 컴포넌트 자체가 배열의 형태로 띄우고 있어서
아래와 같이 코드를 입력해도 문제없이 정상적으로 실행된다
그래서 map() 함수로 배열로 반환하도록 하는 것이다

[<Comment
    userId={tcommentList[0].userId}
    commentText={commentList[0].commentText}/>,
<Comment
    userId={tcommentList[1].userId}
    commentText={commentList[1].commentText}/>,
<Comment
    userId={tcommentList[2].userId}
    commentText={commentList[2].commentText}/>]

그런데 이렇게 코드를 실행하면 '리스트의 각 원소는 유일한 'key' props을 가져야 한다는 내용의 경고메시지가 나오기 때문에 map() 함수의 return 값에 id props를 추가해서 유일한 key값을 준다

{commentList.map(comment => {
  return (
    <Comment
      key={comment.id}
      userId={comment.userId}
      commentText={comment.commentText}
    />
  );
})}
profile
새로운 것을 도전하고 노력한다

0개의 댓글