Home > database >  Binding element 'children' implicitly has an 'any' type.ts(7031) in Next.js
Binding element 'children' implicitly has an 'any' type.ts(7031) in Next.js

Time:12-04

While developing my personal portfolio using Next.js, I ran into an error where the prop "children" was not working. I am using tsx.

Layout.tsx

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

I tried using other props, defining the props, like I was from tutorials online, but none of them worked. ;(

CodePudding user response:

Your filetype is .tsx, which is a TypeScript filetype. You have to either define the types of the props, or change the file's name to Layout.js to convert it to vanilla JavaScript.

If you want to use TypeScript:

import { ReactNode } from "react";
import styles from "./layout.module.css";

const type LayoutProps = {
  children: ReactNode;
  // Your other props here.
}

export default function Layout({ children, ...props }: LayoutProps) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

The issue is that when TypeScript doesn't know the type of something, it will assume the type is any and complain. You could explicitly set the type as any to solve this problem, as well, but this is considered bad practice:

export default function Layout({ children, ...props }: any) {
  return (
    <>
      <main className={styles.main} {...props}>{children}</main>
    </>
  );
}

CodePudding user response:

You are not destructuring the props object correctly. When you use the spread operator (...), it will spread out all the key-value pairs in the object as individual props. Since you have already destructured the children prop, it will not be included in the object that you spread. You can either add the children prop to the spread operator, or destruct all.

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
return (
<>
<main className={styles.main} {...props} {...{children}}>{children}</main>
</>
);
}

Or destructure all the props in one:

import styles from "./layout.module.css";

export default function Layout({ children, ...props }) {
return (
<>
<main className={styles.main} {...props}>{children}</main>
</>
);
}

Either way will fix the children prop.

  • Related