Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`getStaticProps` to populate page header/footer

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?

like image 540
cwj Avatar asked Sep 20 '25 05:09

cwj


1 Answers

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>
  )
}
like image 199
Noodles Avatar answered Sep 22 '25 21:09

Noodles