Search code examples
reactjsreact-hooksnext.jsparentchildren

Passing state from parent to children in React Nextjs


I am a beginner in React and I am facing an issue to pass a state from parent to children. That's my code :

import Footer from './Footer';
import Header from "./Header";

export default function Layout({setPage, children}) {
    return <>
        <Header setPage={setPage}/>
            {children}
        <Footer/>
    </>
}

At this step, I get the setPage state and I can pass it successfully to the Header component for example. However, {children} don't get it. Is there a way to pass the setPage state to {children} ?

Thanks,

I tried useContext hook but didn't work...


Solution

  • Assuming you are using this Layout component to wrap certain pages content, I don't think you'll need to do this. Follow along:

    Probably, you'll use this component as follows:

    import { useState } from "React";
    import Layout from "../components/Layout";
    import OtherComponent from "../components/OtherComponent";
    
    export default function HomePage() {
      const [page, setPage] = useState();
    
      return (
        <Layout setPage={setPage}>
          <OtherComponent setPage={setPage}/>
        </Layout>
      );
    };
    

    Because you'll need to know which children will use that prop. React does have some ways to do this that you asked, but it's discouraged as it fit a super small set of cases.

    Keep up learning, good luck!

    Edit 1: To complement the usage, you can change what is rendered on the screen using that state like this:

    /* previous imports */
    import YetOtherComponent from "../components/YetOtherComponent";
    
    export default function HomePage() {
      const [page, setPage] = useState(0); /* setting the default inside the parenthesis */
    
      return (
        <Layout setPage={setPage}>
          {page === 1 /* checking which component should render */
            ? (<OtherComponent setPage={setPage}/>)
            : page === 2
            ? (<YetOtherComponent setPage={setPage}/>)
            : /* As many options as you want */
          }
          
        </Layout>
      );
    };
    

    This way not all of them would display at all times, only when the respective page value is equal to the component that must be shown.