react children 쓸 때 다양한 자식 요소들 구별하기

Henrique·2024년 10월 3일

리액트 짧막 지식

목록 보기
9/10

좋은 질문이에요! children을 하나로 받으면 다양한 자식 요소들을 구별하기 어려울 수 있습니다. 이 경우 여러 개의 자식 요소를 구별하고 싶다면, 몇 가지 방법을 사용할 수 있습니다.

1. 명명된 props를 사용하는 방법

children은 기본적으로 모든 자식 요소를 하나의 props로 전달하지만, 여러 개의 자식 컴포넌트를 구별해서 사용하고 싶을 때는 각각을 별도의 명명된 props로 전달할 수 있습니다. 즉, children 외에도 추가로 명명된 props를 만들어 여러 자식 컴포넌트를 구별할 수 있습니다.

예시:

// Wrapper.js
import React from 'react';

const Wrapper = ({ header, footer, children }) => {
    return (
        <div style={{ border: '2px solid black', padding: '20px' }}>
            <div>{header}</div>  {/* header props */}
            <h1>Wrapper Component</h1>
            <div>{children}</div>  {/* 일반적인 children */}
            <div>{footer}</div>  {/* footer props */}
        </div>
    );
};

export default Wrapper;

이렇게 하면 여러 가지 props로 다양한 자식 컴포넌트를 구분해서 사용할 수 있습니다.

사용법:

// App.js
import React from 'react';
import Wrapper from './Wrapper';

const App = () => {
    return (
        <Wrapper
            header={<h2>This is the header</h2>}   {/* header로 전달 */}
            footer={<p>This is the footer</p>}     {/* footer로 전달 */}
        >
            {/* 이 부분이 기본 children으로 전달 */}
            <p>This is the main content inside Wrapper!</p>
            <button>Click me!</button>
        </Wrapper>
    );
};

export default App;

2. React의 children을 배열로 다루는 방법

children을 배열처럼 다룰 수 있습니다. children이 여러 개일 때 React의 children API를 사용하여 각 자식 요소를 구분할 수 있습니다.

예시:

// Wrapper.js
import React from 'react';

const Wrapper = ({ children }) => {
    const [header, main, footer] = React.Children.toArray(children); // 배열로 변환 후 분해

    return (
        <div style={{ border: '2px solid black', padding: '20px' }}>
            <div>{header}</div>  {/* 첫 번째 자식은 header로 */}
            <h1>Wrapper Component</h1>
            <div>{main}</div>    {/* 두 번째 자식은 main */}
            <div>{footer}</div>  {/* 세 번째 자식은 footer */}
        </div>
    );
};

export default Wrapper;

사용법:

// App.js
import React from 'react';
import Wrapper from './Wrapper';

const App = () => {
    return (
        <Wrapper>
            <h2>This is the header</h2>  {/* 첫 번째 자식 */}
            <p>This is the main content!</p>  {/* 두 번째 자식 */}
            <p>This is the footer content!</p>  {/* 세 번째 자식 */}
        </Wrapper>
    );
};

export default App;

3. props.children에 컴포넌트 구분을 위한 key 부여

다수의 children을 구분하고 싶을 때 key를 사용하여 자식 컴포넌트의 타입이나 역할을 구분할 수 있습니다.

예시:

// Wrapper.js
import React from 'react';

const Wrapper = ({ children }) => {
    return (
        <div style={{ border: '2px solid black', padding: '20px' }}>
            {React.Children.map(children, (child) => {
                if (child.key === 'header') {
                    return <div style={{ color: 'blue' }}>{child}</div>;
                }
                if (child.key === 'footer') {
                    return <div style={{ color: 'green' }}>{child}</div>;
                }
                return child;  // 기본 children 처리
            })}
        </div>
    );
};

export default Wrapper;

사용법:

// App.js
import React from 'react';
import Wrapper from './Wrapper';

const App = () => {
    return (
        <Wrapper>
            <h2 key="header">This is the header</h2>  {/* key를 통해 구분 */}
            <p>This is the main content!</p>
            <p key="footer">This is the footer content!</p>  {/* key를 통해 구분 */}
        </Wrapper>
    );
};

export default App;

요약:

  • 명명된 props 사용: 여러 props를 명명하여 자식 컴포넌트를 구분할 수 있습니다 (예: header, footer).
  • 배열로 관리: React.Children.toArray()를 사용하여 여러 children을 배열처럼 다룰 수 있습니다.
  • key 사용: key를 통해 자식 컴포넌트를 구분하고 조건부로 렌더링할 수 있습니다.

이 방법들은 자식 요소가 많거나, 서로 구별해야 할 때 매우 유용하게 쓰입니다.

0개의 댓글