I have a dynamic route and I am trying to show the title in url and pass (hide) the id to my dynamic route and use id in getStaticProps. I have found that I can't pass data easily in nextjs as we used to pass with react router or other client routing libraries.
I am following this answer but when I console.log(context.params) I can't see the id passed from Link, what am I doing wrong here ?
// index.js
<Link
href={{
pathname: `/movie/[title]`,
query: {
id: movie.id, // pass the id
},
}}
as={`/movie/${movie.original_title}`}
>
<a>...</a>
</Link>
// [movieId].js
export async function getStaticProps(context) {
console.log(context.params); // return { movieId: 'Mortal Kombat' }
return {
props: { data: "" },
};
}
The context parameter is an object containing the following keys:
params contains the route parameters for pages using dynamic routes. For example, if the page name is [id].js , then params will look like { id: ... }. - Docsexport async function getStaticProps(context) {
console.log(context.params); // return { movieId: 'Mortal Kombat' }
return {
props: {}, // will be passed to the page component as props
}
}
If the dynamic page looks like /pages/[movieId].js you can access pid in context.params.movieId .
You can't access "Query String" in getStaticProps because as the docs state,
Because
getStaticPropsruns at build time, it does not receive data that’s only available during request time, such as query parameters or HTTP headers as it generates static HTML.
If you need "Query String", you can make use of getServerSideProps,
export async function getServerSideProps(context) {
console.log(context.query);
return {
props: {}, // will be passed to the page component as props
}
}
About that Link, you should pass the same value as a key for query which you use for dynamic pathname:
<Link
href={{
pathname: `/movie/[title]`,
query: {
title: movie.id, // should be `title` not `id`
},
}}
as={`/movie/${movie.original_title}`}
>
</Link>;
And then in /pages/[title].js,
export async function getStaticProps(context) {
console.log(context.params); // return { title: 'Mortal Kombat' }
return {
props: {}, // will be passed to the page component as props
}
}
Note how title is being used as the key, both in filename and the query object in Link.
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