I have a component which checks a path name and acts on it:
const router = useRouter();
const path = router.pathname;//props.location.pathname;
const p = path.split('/').filter((s) => s !== "")
let submissionId = p[0] == 's' && p[1]
const submission = useQuery(SUBMISSION, {
variables: {
id: submissionId
},
skip: submissionId === false
})
This works fine in a bog standard react app but nextjs redirects toa 404.
Is tehre a way to set up a pattern for nextjs to ignore none-existant routes and allow the component code to handle it?
Next. js has a file-system based router built on the concept of pages. When a file is added to the pages directory, it's automatically available as a route. The files inside the pages directory can be used to define most common patterns.
Create a new page named article. js inside the pages folder. Users can implement nested routes by simply nesting folders inside the pages folder just make sure that the file and folder name are the same. Now if you navigate to the URL localhost:300/article/competitive-programming you will see the desired results.
Unlike the server-side rendering APIs, you can use client-side data fetching at the component level.
I'm not sure I've understood clearly what you want, but you need to have defined page in the pages folder if you don't want Next.js to redirect to 404. However, you could use dynamic routes to make component which will do what you want.
Create a file named [dynamic].js in the pages folder:
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>
If you are using zeit now v2 then you can check out the Wildcard Routes here.
Basically in your now.json
will have a filesystem handler and a wildcard handler as below
{
"routes": [
{ "handle": "filesystem" },
{ "src": "/.*", "status": 404, "dest": "SOME_PAGE_HERE" } // <-- this is where all the non-existent routes will be routing to
]
}
Just replace the SOME_PAGE_HERE
with your route as what you have declared in exportPathMap
from the file next.config.js
.
Example: /contact
, about-us
and so on.
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