Type TypeScript React Functions
These are the best typings for React function components in TypeScript.
React.FC no more
React.FC
was a nice shortcut. But it seems to actually create trouble down the line -- eg, in generics, defaultProps and return types.
Simple and makes sense
Instead, do what's simple and makes sense. Just type your props and return type.
import React from 'react'
interface CompProps {
thing: 'one' | 'two'
}
function Comp(props: CompProps): React.ReactNode {
return <div>Check this {props.thing}</div>
}
Children prop
You can type children yourself or use the helper.
Manually, yourself:
import React from 'react'
interface CompProps {
children: React.ReactNode
thing: 'one' | 'two'
}
function Comp(props: CompProps): React.ReactNode {
return <div>Check this {props.thing}: {props.children}</div>
}
Or with the helper:
import React from 'react'
interface CompProps {
thing: 'one' | 'two'
}
function Comp(props: React.PropsWithChildren<CompProps>): React.ReactNode {
return <div>Check this {props.thing}: {props.children}</div>
}