I can't figure out how to make this work in Typescript. I've got a custom React component which should accept only a certain type of React components as children. I thought I could do something like this, but it doesn't work:
interface ChildProps {
firstName?: string;
lastName?: string;
}
interface ParentProps {
children: Child[]
}
const Child = ({firstName, lastName}: ChildProps) => {return <div>child</div>}
const Parent = ({children}:ParentProps) => {
return <div>{children}<div>
}
<Parent>
<Child> {/* should work */}
<Child> {/* should work */}
<Child> {/* should work */}
<div>this should throw error. Right?</div>
</Parent>
What I was hoping was that I could enforce that only Child
components are handed to the parent, and I thought it was easy to do, but I'm a bit stumped. I've tried children: Child[]
, and children: JSX.Element<Child>[]
, and a few other things.
I found this SO question, but I can't quite make sense out of it: Typescript: how to set type of children in React Component?
I'm sure it's something dumb I'm doing. Any advice is appreciated. Thanks!!
You can't put a contraint on the type of children, but you can do selective rendering of the children (or throw an exception while running).
Take a look at this code:
private getCorrectChildren(): JSX.Element[] {
const result: JSX.Element[] = [];
React.Children.forEach(this.props.children, child => {
if (React.isValidElement(child)) {
if (child.type === MyTypeOfChildHere) {
result.push(child);
}
}
});
return result;
}
This method can be called in the render()
method and will only return children of the right type. You can, of course, throw an error if the child.type
is different than the one you are expecting.
PS. This is quite verbose and can optimized to be a smaller method, but this is easier to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With