소문자로 시작하는 children은 props객체의 하나의 속성이고, 대문자 Children은 React에서 children props를 효과적으로 다룰 수 있는 API입니다.
React에서는 다양한 형태의 children을 받습니다.
1. 문자열
2. 변수
3. html 요소
4. React 컴포넌트
5. 함수
6. null
7. 여러개의 html 요소
const Basic = () => {
const HelloWorld = ({ children }) => {
console.log('children', children) // children에 대한 값 log
return <div>hello world</div>
}
const arr = [1, 2, 3]
const obj = { a: 1, b: 2 }
const Button = () => {
return <button>이건 버튼</button>
}
return (
<div style={{ width: '200px' }}>
<HelloWorld>문자열</HelloWorld>
<HelloWorld>{arr}</HelloWorld>
<HelloWorld>{obj}</HelloWorld>
<HelloWorld>
<input type="text" />
</HelloWorld>
<HelloWorld>
<Button />
</HelloWorld>
<HelloWorld>
{() => {
return 'hi'
}}
</HelloWorld>
<HelloWorld>
<Button />
<input type="text" />
<br />
</HelloWorld>
</div>
)
}
children에 대한 값을 이미지와 같이 확인할 수 있습니다.
여기서 자세히 볼 부분은 HTML엘리먼트, React컴포넌트를 children일때 객체 형태의 차이를 확인할 수 있습니다.
추가적으로 여러개의 요소를 children으로 전달할 경우, 배열 형태로 children에 접근할 수 있습니다.
이 처럼 React는 컴포넌트의 자식으로 매우 다양한 형태의 데이터들이 사용할 수 있도록 설계되어 있기때문에, React에서는 Children이라는 별도의 API를 통해서 childen props를 다룰 수 있게 도와줍니다.
React.Children을 콘솔에 찍어보면 아래와 같은 함수로 이루어져 있는걸 확인할 수 있습니다.
function Map({ children }) {
return React.Children.map(children, (child, i) =>
i % 2 === 0 ? <b>{child}</b> : <u>{child}</u>
);
}
function ForEach({ children }) {
let count = 0;
React.Children.forEach(children, (child) => {
count += child.length;
});
return (
<>
{children}
{`(총 글자수: ${count})`}
</>
);
}
function Count({ children }) {
const count = React.Children.count(children);
return (
<>
{children}
{`(총 자식수: ${count})`}
</>
);
}
function ToArray({ children }) {
const array = React.Children.toArray(children);
return array.filter((child, i) => i % 2 === 0);
}
function Only({ children }) {
return React.Children.only(children);
}