Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use React.PropsWithChildren

In what to me seems like two similar setups, on one machine I was allowed to call

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />

Where MyApp had the class signature

export interface IMyAppProps {
  accountId: string;
  dispatch: any;
}
    class MyApp extends React.Component<IMyAppProps, IMyAppState> {

On the other machine, running npm run-script build fails with

TypeScript build error TS2322: Type ' ... ' is not assignable to type ' ... '

Property 'children' does not exist on type 'IntrinsicAttributes & Pick<IMyAppProps, "accountId">'

Versions used on both machines react-scripts-ts 4.0.8, typescript 3.4.5.

Changing the class definition to this made it work on both machines

class MyApp extends React.Component<React.PropsWithChildren<IMyAppProps>, IMyAppState> {

I am unsure why it works in one setup and not the other. When do I wrap my props interface in React.PropsWithChildren?

My best guess would be that the change is to be found in a typings file for React or for a React-related package.

like image 462
Thorkil Værge Avatar asked Nov 15 '19 16:11

Thorkil Værge


People also ask

What is the use of props children?

Props is simply an abbreviation for properties. In React, we utilize props to send data from one component to another (from a parent component to a child component or multiple children components). They come in handy when you want the data flow in an app to be dynamic.

What type is props children?

Class components So, the type of the children prop in a class component is ReactNode as well.

What is ReactNode?

A React node is defined as: a light, stateless, immutable, virtual representation of a DOM node. React nodes are not real DOM nodes (e.g., text or element nodes) themselves, but a representation of a potential DOM node. The representation is considered the virtual DOM.


1 Answers

I don't know why it worked on one machine but not the other but I don't think that's the right way to use the children property.

Instead of this ...

<MyApp
        accountId={this.props.accountId}
        children={toggleButton} />

... I think the purpose of children is to let you call something like this ...

<MyApp accountId={this.props.accountId}>
  <ToggleButton/>
</MyApp>

... or something like that.

The child or children -- <ToggleButton/> in my example above -- might be a React element, or text (a text node), or undefined if there is no child, or maybe an expression like {toggleButton} which evaluates to one of the child types.

like image 121
ChrisW Avatar answered Oct 22 '22 17:10

ChrisW