Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript error: Property 'children' does not exist on type 'ReactNode'

export const PageViewTracker = ({ children }: ReactNode): ReactElement => {

    usePageView();

    return children;
};

Problem:

This function returns error »Property 'children' does not exist on type 'ReactNode'«

My approach to solution:

I tried out several types but only any works which is not what I want. Usually I used ReactNode for children props and it worked fine. In this case TypeScript seems to have issues.

like image 588
Christoph Avatar asked Nov 29 '19 14:11

Christoph


People also ask

What is ReactNode TypeScript?

The ReactFragment , which is included in the ReactNode type, includes an empty interface. Due to the way that TypeScript handles excess property checks, this means that the ReactNode type will accept any object except an object literal. For almost all intents and purposes, it is functionally equivalent to an any type.

What is the type of children in React?

The react docs explain the following types can be used as children: string literals (also includes numbers which are coerced to HTML strings) JSX children (aka, nested react components) functions (for custom components that accept functions)

What is IntrinsicAttributes?

IntrinsicAttributes interface can be used to specify extra properties used by the JSX framework which are not generally used by the components' props or arguments - for instance key in React. Specializing further, the generic JSX.

How do you pass props in TypeScript?

To pass an object as props to a component in React TypeScript: Define an interface for the type of the object. Pass an object of the specified type to the child component, e.g. <Employee {... obj} /> .


1 Answers

You can simply write it like this:

export const PageViewTracker = ({ children }: {children: ReactNode}): ReactElement => {

    usePageView();

    return children;
};

Note that I change ({ children }: ReactNode) to ({ children }: {children: ReactNode})

like image 117
ntholi Avatar answered Sep 21 '22 09:09

ntholi