Search code examples
javascriptreactjstypescriptreact-functional-component

Passing child nodes to a functional react component written typescript


What's the correct way to pass child nodes using the children keyword in a React component written in typescript, when using named functions instead of arrow functions?

In an arrow function I can write something like this:

const MyComponent: React.FC = ({children}) => {
   return <div>{children}</div>
}

export default MyComponent;

But how do I do the same thing with a normal function? I tried

import React from "react";

function MyComponent({children}): JSX.Element{
   return <div>{children}</div>
}

export default MyComponent;

But eslint throws the following error:

var children: any
Object pattern argument should be typed. eslint(@typescript-eslint/explicit-module-boundary-types)
'children' is missing in props validation eslint(react/prop-types)

I can get rid of the error by exporting ReactNode from React.

import React, { ReactNode } from "react"

function MyComponent({children}: ReactNode): JSX.Element{
   return <div>{children}</div>
}

export default MyComponent;

But is this considered a viable way to go about this, or is there something else that's considered best practice?


Solution

  • You need to give the children param the correct type..

    Something like this should work..

    function MyComponent({ children }: {children: React.ReactNode}): JSX.Element {
      return <div>{children}</div>;
    }