I am building a project in Next. Currently, I have a custom App component that mounts a Header and Footer component.
Now I want to populate the content of the header/footer from an API (at build time since it won't change very frequently). However, getStaticProps
is only available for pages, not components.
How do I fetch the data at build time and pass it to the header/footer components?
Assuming App
is rendered on the index page inside pages
, you just pass it down the drain.
pages/index.js
import App from '../components/App'
const Index = ({data}) => {
return(
<div>
<App data={data} />
</div>
)
}
export const getStaticProps = async () => {
const res = await fetch('...')
const data = await res.json()
return { props: { data } }
}
And then in your App component you access it using props
.
components/App.js
import Header from './Header'
import Footer from './Footer'
const App = (props) => { // I believe you can also use {data} directly instead of props
return(
<div>
<Header data={props.data} />
<Footer data={props.data} />
</div>
)
}
And then you do the same thing in your Header
and Footer
component.
components/Header.js
const Header = ({data}) => {
return(
<div>
{data}
</div>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With