I've just started learning Next.js, so thanks for your patience with my question. I'm trying to generate dynamic pages (and routes) from data loaded from a local JSON file (data.json
). I will not be doing this in production - just trying to learn Next.js.
partial file structure
|
|- pages
|- members
|- [role].js
|- index.js
|- assets
|- data.json
data.json
{
"people": [
{
"name": "Amy",
"role": "administrator"
},
{
"name": "Bob",
"role": "manager"
},
]
}
Desired result:
I'd like to be able to navigate to /members/administrator
and have the page be rendered with the person's name ("Amy").
I've read this doc regarding getStaticProps
, something that I know will be involved.
I've also tried using this tutorial. In my version of the problem, I am using typescript, but I am just looking for a simple, js/jsx solution for now. Thank you!
CodePudding user response:
To get the data you can use getServerSideProps() like this:
export async function getServerSideProps() {
const data =
await require("/path/data.json");
return {
props: {
data,
},
};
}
And then get the role assigned with useRouter()
import { useRouter } from "next/router";
And get the role from router query:
const { role } = router.query;
And don't forget to pass the data to your functional component
export default function Role({ data })