Home > front end >  Reusing getStaticProps in Next.js
Reusing getStaticProps in Next.js

Time:02-10

I'm creating a blog with Next.js and GraphCMS, and I have an ArticleList component that appears on multiple pages (e.g. on my homepage, under each article as a recommendation, etc.).

However, since the article list is being populated from my CMS, I'm using getStaticProps. And since I can't use getStaticProps on the component-level, I'm re-writing the same getStaticProps function on every single page. Is there any way for me to easily reuse this code and share it across pages?

Would love to know if there are any best practices for this. Thanks!

enter image description here

CodePudding user response:

You could define your getStaticProps function in a separate file, using a re-export, for example:

// lib/getStaticProps.js

export function getStaticProps(context) {
  return {
    props: {
      // some cool props
    },
  }
}
// pages/index.js

export default function Page(props) {
  // ...
}

export { getStaticProps } from "../lib/getStaticProps"
  •  Tags:  
  • Related