Next JS Layout component, pass props to children
Have you considered using React's Context API? The idea is that when using the Context API your component's state get's lifted, to be managed at a global scale. If a component needs a prop, instead of passing props down manually (prop drilling) you can simply wrap you component in what's known as a context provider. This will allow that Component to access the global state of your application. This is good because, when your application gets bigger, you may need to pass props down through many components which can clutter and add unneeded confusion.
React provides some great documentation to set your React application up to use the Context API. Highly recommend checking it out!
Try this
import Header from "../components/header";import Footer from "../components/footer";import { Fragment } from "react";export default function Layout({ children, ...pageProps }) { function recursiveMap(children, fn) { return React.Children.map(children, child => { if (!React.isValidElement(child) || typeof child.type == 'string') { return child; } if (child.props.children) { child = React.cloneElement(child, { children: recursiveMap(child.props.children, fn) }); } return fn(child); }); } // Add props to all child elements. const childrenWithProps = recursiveMap(children, child => { // Checking isValidElement is the safe way and avoids a TS error too. if (isValidElement(child)) { // Pass additional props here return cloneElement(child, { currentUser: { ...user } }) } return child; }); return ( <Fragment> <Header isRegisterPage={pageProps.isRegisterPage} isLoginPage={pageProps.isLoginPage} outHome={pageProps.outHome} /> {childrenWithProps} <Footer /> </Fragment> );}
You can use React's cloneElement
to achieve that.
React.cloneElement(children, { isRegisterPage: pageProps.isRegisterPage, isLoginPage: pageProps.isLoginPage, outHome: pageProps.outHome})
Complete example in your case:
import Header from "../components/header";import Footer from "../components/footer";import React, { Fragment } from "react";export default function Layout({ children, ...pageProps }) { return ( <Fragment> <Header isRegisterPage={pageProps.isRegisterPage} isLoginPage={pageProps.isLoginPage} outHome={pageProps.outHome} /> { React.cloneElement(children, { isRegisterPage: pageProps.isRegisterPage, isLoginPage: pageProps.isLoginPage, outHome: pageProps.outHome }) } <Footer /> </Fragment> );}