I am currently in the process of optimising a number of React SFC components with the use of React.memo
.
Most of these components have children. The project also uses TypeScript.
I was starting to get the impression that memo components did not support children as I was presented with the following error message every time there was an error:
Property 'children' does not exist on type 'IntrinsicAttributes & object'
It turns out this only applies when I provide a Props type to the component. E.g.
const MyComponent: React.SFC<PropType>
If I remove the prop type (as below) then the error does not occur.
const MyComponent: React.SFC
Of course, I need the prop type in most every case.
I have setup a Code Sandbox that emulates the issue:
https://codesandbox.io/s/cool-keldysh-urddu?fontsize=14&hidenavigation=1&theme=dark
tl;dr: why do React.memo components not accept the child prop when a type has been provided for the component props?
There is no way to pass props up to a parent component from a child component. We will revisit this caveat later in this tutorial. It's also important to note that React's props are read only (immutable). As a developer, you should never mutate props but only read them in your components.
While there is no direct way to pass data from the child to the parent component, there are workarounds. The most common one is to pass a handler function from the parent to the child component that accepts an argument which is the data from the child component. This can be better illustrated with an example.
Define the function in the parent component. Pass it as a prop to the child component, e.g. <Child handleClick={handleClick} /> . Use the function in the child component.
To pass props, add them to the JSX, just like you would with HTML attributes. To read props, use the function Avatar({ person, size }) destructuring syntax.
This appears to be an issue with the React.memo
typings, it doesn't automatically pass through children props. There's a discussion on the DefinitelyTyped repo.
For now, you can manually specify the children
prop:
type ChildProps = {
name: string;
children: React.ReactNode;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With