Creating a React component that contains children can be as easy as including a children
property and including {props.children}
in the Return function. But knowing the proper type to use for the children
property (when using TypeScript) can get complicated, so it's better to use one of the two officially supported types.
While we can type the children
property as ReactNode
, my preference is to use the PropsWithChildren
type, which handles the children property and its typing for us.
TestComponent.tsx:
import React, { PropsWithChildren } from "react";
type TestWrappingComponentProps = {
beforeText?: string;
afterText?: string;
};
export const TestWrappingComponent = (props: PropsWithChildren<TestWrappingComponentProps>) => {
return (
<>
<div>Before: {props.beforeText}</div>
{props.children}
<div>After: {props.afterText}</div>
</>
)
}
Using it in another component:
import { TestWrappingComponent } from "somePath/TestWrappingComponent";
<TestWrappingComponent beforeText="text before children" afterText="text after children" >
<button onClick={() => { alert('clicked'); }}>test button</button>
<div>test div</div>
Some plain text...
</TestWrappingComponent>
Credit
With help from: https://blog.logrocket.com/using-react-children-prop-with-typescript/