Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Children prop to React Memo component

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?

like image 357
AdamMcquiff Avatar asked Nov 15 '19 10:11

AdamMcquiff


People also ask

How do you pass the props kids in React?

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.

Can we pass data from child component to parent component in React?

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.

How do you pass a function to a child component via props?

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.

How do I pass a prop to a 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.


1 Answers

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;
};
like image 152
Richard Avatar answered Oct 02 '22 20:10

Richard