본문 바로가기

프론트엔드 개발/React - 이론

[실습] 댓글 컴포넌트 만들기 (리액트)

1. 폴더 구조

2. Comment.jsx

import React from "react";

const styles = {
    wrapper: {
        margin: 8,
        padding: 8,
        display: "flex",
        flexDirection: "row",
        border: "1px solid grey",
        borderRadius: 16,
    },
    imageContainer: {},
    image: {
        width: 50,
        height: 50,
        borderRadius: 25,
    },
    contentContainer: {
        marginLeft: 8,
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
    },
    nameText: {
        color: "black",
        fontSize: 16,
        fontWeight: "bold"
    },
    commentText: {
        color: "black",
        fontSize: 16,
    }
}

const Comment = (props) => {
    return (
        <div style={styles.wrapper}>
            <div style={styles.imageContainer}>
                <img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png" 
                alt=""
                style={styles.image} />
            </div>

            <div style={styles.contentContainer}>
                <span style={styles.nameText}>{props.name}</span>
                <span style={styles.commentText}>{props.comment}</span>
            </div>
        </div>
    );
}


export default Comment;

길어 보이는데, Style은 CSS 용이어서 그리 중요한 부분은 아니다. 잘 확인해야할 부분은,  해당 Comment 컴포넌트는 props에서 이름과 댓글을 받아서 뿌린다는 것이다.

 

2. CommentList.jsx

import React from "react";
import Comment from "./Comment";

const comments = [
{
    name: "전수민",
    comment: "끝까지 가면 내가 다 이겨"
},
{
    name: "이민혁",
    comment: "보고 싶다 친구들아"
},
{
    name: "차차",
    comment: "다 함께, 차차차"

}
];

const CommentList = (props) => {
    return (
        <div>
            {comments.map((comment) => {
                return (
                    <Comment name={comment.name} comment={comment.comment}/>
                );
            })}
        </div>
    )
}

export default CommentList;

일단 사용자로부터 값을 받는 것은 따로 하지 않았고,  정적인 배열의 값들을 받아서 배열의 크기만큼 Comment 컴포넌트를 반복하여 값을 보내고 있다. 이때 사용한 것이 map 함수인데, map 함수는 배열의 원소 하나하나를 순회한다는 특징이 있다. 

3. 최상단 index.jsx

 ReactDOM.render(
    <React.StrictMode>
      <CommentList/>
    </React.StrictMode>,
    document.getElementById('root')
  )

이렇게 바꿔준다. 

 

4. 시연 화면