Home > Back-end >  Error: Do not pass children as props. Instead, nest children between the opening and closing tags
Error: Do not pass children as props. Instead, nest children between the opening and closing tags

Time:10-21

I have found a similar issue online but the solutions havent helped my course. I am new to typescript and so I assume I could be missing something very simple. I have a simple app on Nextjs. It renders fine but I get this error when I try to build it locally:

import { useState } from 'react'
import Sidebar from './sidebar';
import LayoutContent from './layout_content';

type Props = {
  children: JSX.Element | JSX.Element[]
}
const Layout = ({ children }: Props) => {
  

  const [open, setOpen] = useState(true);
  const toggle = () => {
    setOpen(!open)
  }
  return (
    <>
      <Sidebar onClick={toggle} sidebar={open} />

      <LayoutContent children={children} sidebar={open}/>
     
    </>
  )
}

export default Layout;

layout_content.tsx

const LayoutContent = ({ children , sidebar}: {children:any, sidebar:any}) => {
      return(
      <>
          <div>
              {children}
          </div>
      </>
)}

CodePudding user response:

You can not pass a react node to layout content as props. you can just wrap children inside layout content component.

layout_content.tsx

import React from "react";

const LayoutContent = ({ children , sidebar}: {children:React.ReactNode, sidebar:boolean}) => {
      return(
      <div>
         {children}
      </div>
   )}

in your main layout

import React, { useState } from 'react'
import Sidebar from './sidebar';
import LayoutContent from './layout_content';

type Props = {
  children: React.ReactNode
}
const Layout = ({ children }: Props) => {
  

  const [open, setOpen] = useState<boolean>(true);
  const toggle = () => {
    setOpen(!open)
  }
  return (
    <>
      <Sidebar onClick={toggle} sidebar={open} />

      <LayoutContent sidebar={open}>
          {children}
      </LayoutContent>

    </>
  )
}

export default Layout;

CodePudding user response:

It tells you not to pass children prop into your LayoutContent. To pass children, you should just put all you need between opening and closing tags of LayoutContent component, like this

<LayoutContent sidebar={open}>
  {children}
</LayoutContent>

Or even higher where you pass children to Layout component

  • Related