How to pass props to inherited component in next.js

Viewed 111

I have the following index.js page, that uses a layout component:

import Layout from "../components/layout";

export default function Home({posts}) {
  console.log(posts)

  return (
      <Layout posts={posts}>
        <div className="showmore" data-total="total">
              test
          
        </div>

      </Layout>
  )
}

export async function getServerSideProps() {
    const res = await fetch('http://gsr2.localhost.xip.io/api/news')
    const posts = await res.json()

    return {
        props: {
            posts,
        },
    }
}

How do I get the posts in the layout, to use in another component there?

This is my layout, but I only get the children and not anything else.


export default function Layout({children, props}) {
    console.log(children, props);
    return (
        <>
            <Head/>
            <main>{children}</main>
            <News>{props}</News
            <Footer/>
        </>
    )
}
1 Answers

There is a misunderstanding here, when you try to access children and props in you layout, you are trying to get a property props that would have passed to the component.

Instead you should do

({ children, posts })

There you should be able to access to posts.

Related