Home > Enterprise >  how do i make an object pass as a child
how do i make an object pass as a child

Time:10-01

learning react/nextjs...i have a main layout that simply includes two components - footer, and header.

function MainLayout(children) {
    return(
        <div>
            <Header />
            {children}
            <Footer />
        </div>
    );
}

export default MainLayout;

i want this layout to sit within the main page like so:

import {default as Layout} from './MLayout.js';
import {default as Navbar} from './MNavbar.js';    
function MainPage() {
        return(
            <div>
                <Layout children={Navbar} />
            </div>
        );
    }
    
    export default MainPage;

and within that mainpage, i'd like to insert a navbar in between the footer and header of the mainlayout. the navbar will change later, so that's why i want to keep it as a child.

the navbar im using does not use links, it uses buttons instead:

const Navbar = (props, {children}) => {

        const [login, makeLogin] = useState(false);

        function Login(){
            makeLogin(true);
        }

        if (login) {
          return (
              <div>
                  <LoginPage />
              </div>
          )
      }
        else {
          return ( blah blah blah the regular nav bar buttons.
    );
}};

the error i get:

Unhandled Runtime Error
Error: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.

CodePudding user response:

Pass <Navbar/> as children in MainPage to

<MainLayout children={<Navbar />} />

Get { children } in

function MainLayout({ children }) {...}

CodePudding user response:

Destructure the props for your MainLayout and Navbar components by wrapping them in curly brackets:

function MainLayout({ children }) {
const Navbar = ({ children }) => {

currently your code is passing the entire props object, which looks like { children: ... } and is causing your error.

  • Related