JavaScript/TypeScript
타입스크립트에서 children
니비앙
2023. 4. 1. 19:06
JSX.Element
children이 단일 React 요소여야 하는 경우 사용. 여러 요소는 허용하지 않는다.
type Props = {
title: string,
children?: JSX.Element,
};
const Page = ({ title, children }: Props) => (
<div>
<h1>{title}</h1>
{children}
</div>
);
여러 children 사용 가능. 그러나 이렇게 해도 문자열은 허용하지 않는다.
type Props = {
title: string,
children?: JSX.Element | JSX.Element[];
};
이렇게하면 문자열도 가능. 그런데 숫자는 불가능...
type Props = {
title: string;
children:
| JSX.Element
| JSX.Element[]
| string
| string[];
};
React.ReactNode
이 한 줄이면 위의 불편한 점들이 모두 해결된다.
type Props = {
title: string;
children?: React.ReactNode;
};
const Wrapper = ({ children }: Props) => {
return <WrapperDiv>{children}</WrapperDiv>;
};
export default Wrapper;