SW프로그래밍/React
[React] children으로 받은 Element에 Prop 추가하기
고랑이.
2022. 1. 12. 17:06
import { createElement } from "react";
function Container({ children }: { children: JSX.Element | JSX.Element[] }) {
const childArray = Array.isArray(children) ? children : [children];
return (
<>
{childArray.map((child, idx) => {
return createElement(child.type, {
...{
...child.props,
idx: idx,
value: `value${idx}`
}
});
})}
</>
);
}
예시 : <Container>의 자식으로 여러개의 노드를 사용하는 경우
JSX.Element[] 배열을 통해 선언되어 있는 모든 자식 노드를 가져오고,
child를 콘솔에 찍어보면 타입, props값 등 해당 노드의 정보를 가져오거나 확인할 수 있다.
예를들어,
child.props.name이라고 하면 자식노드의 name props 값을 가져와 사용할 수 있다.