Type of children prop in React Typescript
Type of children prop in React Typescript
In difference contexts, you can choose type of 'children' prop as following types:
1. Type JSX.Element: using only for single React Element
If 'children' is list React Element, we can define: children: JSX.Element | JSX.Element[]
export default ICustomPageContext;
type Props = {
title: string,
children: JSX.Element,
};
const Page = ({ title, children }: Props) => (
<div>
<h1>{title}</h1>
{children}
</div>
);
2. Type ReactChild: using for single React Element, string, number
If 'children' is list React Elements, list string, list number, we can define: children: ReactChild | ReactChild[]
type Props = {
title: string;
children?:
| React.ReactChild
| React.ReactChild[];
};
3. Type ReactNode: using for multiple React Elements, strings, number. This is general type for 'children'
If you cannot identify the specific type of 'children', you just use type ReactNode
type Props = {
title: string;
children?: React.ReactNode;
};
4. Type FC (FunctionComponent)
FC is a generic type that takes in the specific type for all the component
The 'children' prop is implicit defined in FC
Because this is implicit, I not suggest using it
type Props = {
title: string,
};
const Page: React.FC<Props> = ({
title,
children,
}) => (
<div>
<h1>{title}</h1>
{children}
</div>
);
Conclusion
- ReactNode include ReactChild and list of ReactChild
- ReactElement is only for React Element
- FC (FunctionComponent) is implicit type that include 'children' props
- Using ReactNode for general
Nhận xét
Đăng nhận xét