When to use React.PropsWithChildren
Asked Answered
M

2

23

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.

Mckellar answered 15/11, 2019 at 16:38 Comment(1)
was wondering this myself as well as a newbie in React, voted up and hopefully we can both get an answerArmagnac
P
11

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.

Picturize answered 6/7, 2020 at 8:7 Comment(0)
G
2

The actual answer has nothing to do with whether you use <MyApp children={...} or <MyApp><Child /></MyApp>. The difference is that in the first example IMyAppProps does not have a children property defined, so TypeScript complains that you can't use it like that. When you wrap it in WithChildren that adds a children property to the interface.

Glucosuria answered 28/5, 2022 at 17:15 Comment(2)
We didn't have this issue until now, we haven't even updated React, then suddenly, boom this explodes in our face for the entire codebase. Where does it come from?Belsen
My guess would be that you probably didn't have this error before because you didn't have @types/react installed so there was nothing for it to check, and thens somebody added it.Glucosuria

© 2022 - 2024 — McMap. All rights reserved.