Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js links refresh the page

I have a Next.js blog with only 2 routes: / and /posts/:slug.

When I'm on /posts/my-post-title, and I click on the back link (to /), all is fine. The page loads fast (no refresh).

When I'm on /, and I click on /posts/my-post-title, the page refreshes and I can't figure out why. Any suggestion?

Links: blog, sources

like image 972
soywod Avatar asked Jun 29 '19 12:06

soywod


2 Answers

I had this issue before, I thought I fixed it but again none of the above helped me solve the issue completely so I'm posting my solution.

Suppose you want to go to slot/[key] route using the link.

Then, in pages folder make a folder with name slot and inside it make a file with name [key].js, Note: Don't forget to put that [].

inside [key].js folder you can simply export the component you want to render. There are many approaches to this, let's not go into it now.

Now, while using Link use it this way,

                 <Link
                      href={'/slot/[key]'}
                      as = {`/slot/${your_dynamic_variable}`}
                    >
                      <a>
                        Go to the slot route
                      </a>
                    </Link>
like image 56
sareek Avatar answered Oct 26 '22 08:10

sareek


I just found the answer...

Because I map dynamically /posts/:slug to /posts?slug=:slug in my config (in order to reach posts.jsx), I need to do the same with the Link component (via the property as).

like image 27
soywod Avatar answered Oct 26 '22 07:10

soywod