You have no excuses now, use this free credit to launch your projects now on Digital Ocean.
Table of contents
Types for React components with children
Types for React components with children
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
Don't settle with Javascript, learn Typescript too
AdIf your Javascript skills are good enough to write some medium complexity applications, you should probably have noticed some of its weaknesses, Typescript was created to solve them, and there are platforms out there, like educative, which can teach you all you need to know about Typescript for a few bucks.
You know React, now what?
AdReact is a library, but there are frameworks based on React which can speed up your development and take care of all the boilerplate that is usually written, one of them, and my personal favorite is Nextjs. If you're looking to take advantage of your react skills maybe you should learn Nextjs.
Don't settle with Javascript, learn Typescript too
AdIf your Javascript skills are good enough to write some medium complexity applications, you should probably have noticed some of its weaknesses, Typescript was created to solve them, and there are platforms out there, like educative, which can teach you all you need to know about Typescript for a few bucks.
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
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
See what Typescript has to say on React at their official documentation