1

I am interested in making a dynamic Navbar fetching datas from mongodb.

This is my structure :

# src

* [components/]
  * [Navbar.js]]
  * [Layout.js]]
* [pages/]
  * [index.js]
  * [_app.js]

Though it is not possible to getServerSideProps inside of Components if I am not mistaken, nor inside of _app.js.

I've heard of getInitialProps but I haven't been able to wrap my head around it and also it would lead into a nasty prop drilling.

_app.js -> Layout -> Navbar

Now, how would you do a Navbar with dynamics links according to what's fetched from mondodb?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Guillaume Ayad
  • 103
  • 1
  • 10
  • Does this answer your question: [Persistent navigation in a NextJs \_app](https://stackoverflow.com/a/65628271/1870780)? You can then use [React Context](https://reactjs.org/docs/context.html) if you want to avoid prop drilling when passing the data down to the components that need it. – juliomalves Oct 08 '21 at 14:43

1 Answers1

0

I think nextJs has a documentation on this topic. https://nextjs.org/docs/basic-features/pages

export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../mongodb')
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}

The idea is to generate a list of paths. But your mongodb needs to be called in the compile time, not runtime.

windmaomao
  • 7,120
  • 2
  • 32
  • 36
  • How does this relate to OP's question? `getStaticPaths` is used to statically generate dynamic _routes_. OP is talking about having a persistent nav bar with dynamic _links_ in it. – juliomalves Oct 09 '21 at 23:12
  • If that is the case, then it's nothing to do with `nextJS`, do just in the regular React way then. – windmaomao Oct 10 '21 at 00:35