DEV Community

Cover image for TypeScript and React Children

TypeScript and React Children

Debbie O'Brien on January 11, 2022

What happens when we pass in children in React? Children is a special prop that allows us to pass in any type of element. It could be a number, a s...
Collapse
 
kkomelin profile image
Konstantin Komelin •

Hi Debbie,

Here is how I play with children:

import { FC, PropsWithChildren } from 'react';

type Props = {
  /* Other custom props */
}
const Component1:FC<PropsWithChildren<Props>> = ({children}) => {
  return (
    <>Component code</>
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anidel profile image
Aniello Del Sorbo •

FC already accepts children, no need for PropsWithChildren.

If you don't want want children, you can use VFC.

Collapse
 
hellatan profile image
dale tan • • Edited

This is no longer true for FC with React 18. You must either use PropsWithChildren or explicitly add a children prop to your type definition.

Thread Thread
 
debs_obrien profile image
Debbie O'Brien •

you're right. thanks for the comment.

Collapse
 
kkomelin profile image
Konstantin Komelin •

Thank you Aniello! Good to know.

Thread Thread
 
debs_obrien profile image
Debbie O'Brien •

thanks guys, will play around with it

Collapse
 
rerodrigues profile image
Renato Rodrigues • • Edited

Nice article! There is only a small mistake on the last example where it reads children: React.ReactChild instead of children: React.ReactNode

Collapse
 
debs_obrien profile image
Debbie O'Brien •

ooops. thanks just corrected it. nice catch

Collapse
 
jaybarls profile image
JamieBarlow •

Hi Debbie, just came across this as it's missing from a number of courses I've used - a little surprising as React props are mentioned, but not the commonly used 'children' prop! Thanks for laying this out so clearly.

Collapse
 
joset98 profile image
joset98 •

Thank you Debbie O'Brien, this post is great, i usually forget whats de diff between params type for children, this cheat post is Gold.

Collapse
 
borisnekezov profile image
Boris Nekezov •

Thank you Debbie, really usefull, short and clear article :)

Collapse
 
smn_riaz profile image
Shahman Riaz •

Thanks everyone.