Card 컴포넌트 안에 버튼이 존재합니다.

이를 children으로 자식 컴포넌트에 전달할 수 있습니다.

 

아래의 코드에서는 <Card></Car>컴포넌트 안쪽에 있는 <button>button</button> 컴포넌트를 전달합니다.

<div>
    {posts.map((post) => {
        return (
            <Card key={post.id} title={post.title}>
                <button>button</button>
            </Card>
        );
    })}
</div>

 

전체코드

import axios from "axios";
import { useState, useEffect } from "react";
import Card from "../components/Card";

const ListPage = () => {
    const [posts, setPosts] = useState([]);

    const getPosts = () => {
        axios.get("http://localhost:3001/posts").then((res) => {
            setPosts(res.data);
        });
    };

    useEffect(() => {
        getPosts();
    }, []);

    return (
        <div>
            <h1>Blogs</h1>
            <div>
                {posts.map((post) => {
                    return (
                        <Card key={post.id} title={post.title}>
                            <button>button</button>
                        </Card>
                    );
                })}
            </div>
        </div>
    );
};

export default ListPage;

 

자식 컴포넌트에서는 부모컴포넌트에서 보내준 컴포넌트를 children 키워드를 통해서 받아 올 수 있습니다.

{children && <div>{children}</div>}를 통해서 보내주는 경우 보내주지 않는 경우로 나눠서 렌더링 할 수 있습니다.

//children을 통해서 내부 컴포넌트를 받아올 수 있다.
const Card = ({ title, children }) => {
    return (
        <div className="card mb-3">
            <div className="card-body">
                <div className="d-flex justify-content-between">
                    <div>{title}</div>
                    {children && <div>{children}</div>}
                </div>
            </div>
        </div>
    );
};

export default Card;

 

결과물

[React] children로 부모컴포넌트에서 자식 컴포넌트로 컴포넌트 전달