Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct typescript type for react children?

I'm trying to properly type the props for a component that maps children:

type Props = {
    children: any
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);

I've been using JSX.Element but that doesn't quite feel right.

like image 539
linuxdan Avatar asked Nov 26 '25 03:11

linuxdan


2 Answers

Looking through the code under DefinitelyTyped it appears that children is typed as ReactNode.

Example:

type Props = {
    children: ReactNode
}

const MyComponent: FunctionComponent<Props> = () => (React.Children.map(children, someMapingFunction);

Note: The ReactNode type can be found in the React namespace:

import React from 'react';

let someNode: React.ReactNode;
like image 56
linuxdan Avatar answered Nov 28 '25 17:11

linuxdan


The children is a prop like any other and can be of any type. It's only special insofar that child JSX elements are automatically mapped to the children prop.

So, while it's usually declared as children?: React.ReactNode, you could declare it as a render prop, or even as a custom type like so:

interface INameProps {
    children: {
        fistName: string,
        lastName: string
    }
}

const Name: React.FC<INameProps> = ({children}) => {
    return <div>{children.fistName} {children.lastName}</div>;
}

And then you can use it like so:

<Name>
    {
        {
            fistName: "John",
            lastName: "Smith"
        }
    }
</Name>

Which is the same as:

<Name
    children={
        {
            fistName: "John",
            lastName: "Smith"
        }
    }
/>
like image 29
Branko Dimitrijevic Avatar answered Nov 28 '25 16:11

Branko Dimitrijevic