Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What TypeScript type should React children be set to?

Here's my layout:

export default function Layout(children:any) {
  return (
    <div className={`${styles.FixedBody} bg-gray-200`}>
      <main className={styles.FixedMain}>
        <LoginButton />
        { children }
      </main>

      <footer>
        <FooterNavigation />
      </footer>
    </div>
  )
}

And my app:

function MyApp({ Component, pageProps }) {
  return (
    <Layout>
      <Component {...pageProps} />
    </Layout>
  )
}

To make my code a little cleaner, I'd like to set Layout(children:any) to an actual type instead of any, but I get this warning on my app page on Component when I change it to Layout(children:ReactNode):

TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes | (IntrinsicAttributes & string) | (IntrinsicAttributes & number) | (IntrinsicAttributes & false) | (IntrinsicAttributes & true) | (IntrinsicAttributes & ReactElement<...>) | (IntrinsicAttributes & ReactNodeArray) | (IntrinsicAttributes & ReactPortal)'.   Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.

It makes sense then that I should set it to Layout(children:IntrinsicAttributes) { but when I do there's no option to import it. What should this be set to?

like image 415
Citizen Avatar asked Dec 01 '22 08:12

Citizen


1 Answers

2022 Edit

The best way to properly type children is to use built-in type FC.

import { FC } from 'react';

If the only prop you expect is children:

const MyComponent: FC = (props) => {};
                       // props includes only children property

If you want to include more props than just children:

interface MyProps {
   name: string;
}

const MyComponent: FC<MyProps> = (props) => {};
                           // props includes children and name properties

Old answer

props is an object - children is a nested field inside props object.

interface LayoutProps {
   children: React.ReactNode;
}

function Layout({ children }: LayoutProps) {
like image 156
kind user Avatar answered Dec 03 '22 23:12

kind user