Reputation: 149
I have a menu component use to navigate internally in my website like :
<Link href="/containers/grades/List" as="/grades">
I use "as" to keep clean my URL but the problem is the navigated page cannot be refreshed; if I refresh the page I get 404 error.
I know that "as" is used for showing a custom address in URL but I need a way to get to the component from URL
in this case, I want to navigate from "/grades"
to "/containers/grades/List"
is there any suggestion?
Upvotes: 4
Views: 3810
Reputation: 739
With <Link href="/containers/grades/List" as="/grades">
you have client side route and for server side just add this below code to your next.config.js;
experimental: {
async rewrites() {
return [
{ source: '/grades', destination: '/containers/grades/List' }
];
}
}
this will wire them up.
Upvotes: 6
Reputation: 575
For dynamic page you would do use the useRouter
for dynamic routing between pages.
import React from 'react'
import { useRouter } from 'next/router'
const Dynamic = () => {
const router = useRouter();
const { dynamic } = router.query;
return (
<div>
My dynamic page slug: {dynamic}
</div>
)
}
export default Dynamic And you can link to it like this:
<Link href="/[dynamic]" as="/dynamic-page-slug">
<a>Link to my Dynamic Page</a>
</Link>
You can also make your custom routes by adding next.config.js file:
// next.config.js
module.exports = {
async redirects() {
return [
// 307 temporary redirect
{
source: "/",
destination: "/under-construction",
permanent: false,
},
// 308 permanent redirect
{
source: "/posts",
destination: "/blog",
permanent: true // permanent redirect
},
// With parameter and custom status code
{
source: "/photos/:id",
destination: "/photo/:id",
statusCode: 303 // see other
}
];
}
};
Upvotes: 1