snippettypescriptreactCritical
How to use children with React Stateless Functional Component in TypeScript
Viewed 0 times
typescriptwithhowcomponentusestatelessfunctionalreactchildren
Problem
Using TypeScript with React we no longer have to extend
However, it doesn't seem to be the case for stateless functional components:
Emits the compile error:
Error:(102, 17) TS2339: Property 'children' does not exist on type
'MyProps'.
I guess this is because there's really no way for the compiler to know that a vanilla function is going to be given
So the question is how should we use children in a stateless functional component in TypeScript?
I could go back to the old way of
So I could define the
First: is
Second: I have to write children as optional (
It seems like I'm missing something. Can anyone provide some clarity on whether my last example is the way to use stateless functional components with children in React?
React.Props in order for the compiler to know that all react component props can have children:interface MyProps { }
class MyComponent extends React.Component {
public render(): JSX.Element {
return {this.props.children};
}
}However, it doesn't seem to be the case for stateless functional components:
const MyStatelessComponent = (props: MyProps) => {
return (
{props.children}
);
};Emits the compile error:
Error:(102, 17) TS2339: Property 'children' does not exist on type
'MyProps'.
I guess this is because there's really no way for the compiler to know that a vanilla function is going to be given
children in the props argument.So the question is how should we use children in a stateless functional component in TypeScript?
I could go back to the old way of
MyProps extends React.Props, but the Props interface is marked as deprecated, and stateless components don't have or support a Props.ref as I understand it.So I could define the
children prop manually:interface MyProps {
children?: React.ReactNode;
}First: is
ReactNode the correct type?Second: I have to write children as optional (
?) or else consumers will think that children is supposed to be an attribute of the component (``), and raise an error if not provided with a value.It seems like I'm missing something. Can anyone provide some clarity on whether my last example is the way to use stateless functional components with children in React?
Solution
You can use
React.PropsWithChildren type for your props:interface MyProps { }
function MyComponent(props: React.PropsWithChildren) {
return {props.children};
}Code Snippets
interface MyProps { }
function MyComponent(props: React.PropsWithChildren<MyProps>) {
return <div>{props.children}</div>;
}Context
Stack Overflow Q#40748397, score: 189
Revisions (0)
No revisions yet.