The following NextJS URL parameters such as React-Router

I'm new to NextJS , it looks so good from the first impression. But after I gave him a chance, I ran into some problems, such as routing URLs with custom parameters, such as a responsive router .

Currently, what can we do with NextJS

https://url.com/users?id:123 

What we need for a better URL pattern

 https://url.com/users/123 

The responsive router has a great example here: https://reacttraining.com/react-router/web/example/url-params

+10
source share
5 answers

this example will help you define your parameterized, named routes. It uses nest / routes and allows you to define your preferred routes. hope this helps you.

https://github.com/zeit/next.js/tree/master/examples/with-next-routes

+10
source

You can use next/link as functions:

 <Link prefetch as={'/product/${slug}'} href={'/product?slug=${slug}'}> 

The link in the browser will display as /product/slug which internally matches /product?slug=slug

You need to have your own server for server side matching:

 server.get("/product/:slug", (req, res) => { return app.render(req, res, "/product", { slug: req.params.slug }) }) 
+8
source

For those late for this party, we now have dynamic routing in the next nine.

Which would allow you to create the structure of the URL in this way, using the file structure and without additional packages.

You can create the pages/user/[id].js file

WITH

 import { useRouter } from 'next/router' const User = () => { const router = useRouter() const { id } = router.query return <p>User: {id}</p> } export default User 
+3
source

I went through the same problem, but I found this package, https://github.com/fridays/next-routes

It works almost the same as a react router, I tried, and it works for me.

+1
source

First Import Router

 import Router from 'next/router' 

Then if you want to use it in the link tag

 <Link href={{ pathname: '/about', query: { name: 'Sajad' } }}> 

If you want to use it in a function or after a callback

 Router.push({ pathname: '/about', query: { name: 'Sajad' }, }) 
0
source

Source: https://habr.com/ru/post/1266258/


All Articles