'How to send date to child components in next using getStatisticProps?
I read that I can use getStatisticProps only in pages area, but can I use a template from components?
I want to send date from pages/index.js
export default function Home({posts}) {
return (
<div>
<Head>
<title>NextJs is so cool</title>
<meta
name="description"
content="my new wonderful page"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
<CustomComponents data={posts}/>
</div>
);
}
export async function getStaticProps(context) {
const res = await fetch('https://example.com/wp-json/wp/v2/posts')
const posts = await res.json()
return {
props: {
posts,
},
}
}
to CustomComponents.js and from there to blog section:
const CustomComponents = ({posts}) => {
return (
<div>
...
<BlogComponent data={posts} />
</div>
);
};
export default CustomComponents;
but there is an error when I use this date in bloc section - posts.title.render[0] do not exist...
const BlogComponent = ({posts}) => {
{posts.title.rendered}
);
};
export default BlogComponent;
where I make an mistake? or just it is not possible?
Solution 1:[1]
You passing it as data={posts}
export default function Home({posts}) {
return (
<div>
<Head>
<title>NextJs is so cool</title>
<meta
name="description"
content="my new wonderful page"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
// You pass posts to child component as name data
<CustomComponents data={posts}/>
</div>
);
}
So in your Child component you should destruct it like this and so on:
// Child.jsx
const CustomComponents = ({data}) => {
return (
<div>
// rest of you code
<BlogComponent data={data} />
</div>
);
};
export default CustomComponents;
Still If you want to pass props to nested component tree (prop drilling) you use Context API to make it easier.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nos nart |
