Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  114] [ 5]  / answers: 1 / hits: 90963  / 2 Years ago, thu, april 7, 2022, 12:00:00

I upgraded to React 18 and things compiled fine. Today it seems every single component that uses children is throwing an error. Property 'children' does not exist on type 'IPageProps'.


Before children props were automatically included in the FC interface. Now it seems I have to manually add children: ReactNode. What is the correct typescript type for react children?


Is this part of the React 18 update, or is something screwed up in my env?


package.json


"react": "^18.0.0",
"react-dom": "^18.0.0",
"next": "12.1.4",
"@types/react": "18.0.0",
"@types/react-dom": "18.0.0",

tsconfig.json


{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"alwaysStrict": true,
"sourceMap": true,
"incremental": true
},
"include": ["src"],
"exclude": ["node_modules"]
}

More From » reactjs

 Answers
4

Although this answer is correct, I want to note that you absolutely don't have to use this PropsWithChildren helper. (It is primarily useful for the codemod, not manual usage.)


Instead, I find it easier to define them manually.


Before


import * as React from 'react';

type Props = {};
const Component: React.FC<Props> = ({children}) => {...}

After


import * as React from 'react';

type Props = {
children?: React.ReactNode
};
const Component: React.FC<Props> = ({children}) => {...}

That is all that's needed.


Or you can stop using React.FC altogether.


import * as React from 'react';

type Props = {
children?: React.ReactNode
};

function Component({children}: Props): React.ReactNode {
...
}

In React, children is a regular prop and is not something special. So you need to define it just like you define all the other props. The previous typings that hid it were wrong.


[#50048] Monday, January 31, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikokorbinm

Total Points: 744
Total Questions: 126
Total Answers: 104

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;