DEV Community

Cover image for Types for React components with children
Eduardo Zepeda
Eduardo Zepeda

Posted on • Originally published at coffeebytes.dev on

Types for React components with children

Image credits to: tranmautritam

Typescript requires that we specify the types for the different variables and function arguments in React. When they are native types it is not intrincate, but for React components it can be different. Here are 3 ways to specify types for React components that contain children as part of their props.

Types With ReactNode

The easiest way is manually, by specifying children as an optional React node.

import React from 'react'

type Props = {
    children?: React.ReactNode
}

const MyComponent = ({ children }: Props) => {
    return (
        <div>
            {children}      
        </div>
    )
}

export default MyComponent

Enter fullscreen mode Exit fullscreen mode

Using React.FC

The second way is to use a FC (Functional Component) object provided by React, which leaves implicit the use of children and also prevents us from returning undefined. Consider that using React.FC is considered by some developers as a bad practice.

import React from 'react'

const MyComponent: React.FC<{}> = ({ children }) => {
    return (
        <div>
            {children}      
        </div>
    )
}

export default MyComponent

Enter fullscreen mode Exit fullscreen mode

React.PropsWithChildren

The last way is to make use of the PropsWithChildren object provided by React which, as its name says, already includes the props with the children component, ready to be used directly.

import React from 'react'

type Props = React.PropsWithChildren<{}>

const MyComponent = ({ children }: Props) => {
    return (
        <div>
            {children}      
        </div>
    )
}

export default MyComponent

Enter fullscreen mode Exit fullscreen mode

See what Typescript has to say on React at their official documentation

Top comments (6)

Collapse
 
m4rcxs profile image
Marcos Silva

good article!

Collapse
 
zeedu_dev profile image
Eduardo Zepeda

Thank you for your comment!

Collapse
 
syedmuhammadaliraza profile image
Syed Muhammad Ali Raza

Good But write more content

Collapse
 
zeedu_dev profile image
Eduardo Zepeda

Thank you for commenting. I think this is one of my shortest articles ever, but I do have some loooooooooong ones in my blog dealing with topics like Artificial Intelligence or Devin AI. Check'em on Coffee bytes. I hope you like them.

Collapse
 
btcorso profile image
Bruno Tiago Corso

Shouldn't be "Props" rather than "props" on the first example?

Collapse
 
zeedu_dev profile image
Eduardo Zepeda

Hello! You're right, my bad. I'll fix it right now, thanks for letting me know!