Roger Peixoto
Roger Peixoto

Reputation: 376

How to change only one component when switching pages with nextjs?

Background

I want to build a web page where, whenever I change the url to another path, it does not trigger navigation, I mean, it does not load the page again; instead, I want this url change to change the properties of one component "x" in the page. Depending on the url path, it would lead the component "x" to load different properties;

Code example

On the example below, depending on the Link clicked, it would show a different value on the empty paragraph line: In case the url path is just '/', it should be empty, but if I click on Link 1 it should show "value1" on the paragraph, and if i click on Link 2 it should show "value2". In both cases, i dont want to trigger navigation, i only want the url to be changed and the value on the paragraph to also change accordingly.

import React from 'react'
import Link from 'next/Link'


const example = ()=>{
    return(
    <div>
        <div>   
        <h1>Example</h1>
        <Link href='/value1'><a>Link 1</a></Link>
        <Link href='/value2'><a>Link 2</a></Link>
        </div>
        <div>
         <p> Value <p>
        </div>
    </div>
    )
}

export default example

Question

How can I do this using NextJS? I know that there is the shallow routing, but according to what I have found on this issue https://github.com/zeit/next.js/issues/3253 there is no certain way of doing this... I know it can be done using react-router, but for the sake of learning nextJS I was wondering how could I do such a thing using this tool.

Thank you for any help!

Upvotes: 6

Views: 6022

Answers (1)

cobrexus
cobrexus

Reputation: 4806

Use Next.js Shallow Routing.

Shallow routing allows you to change the URL without running data fetching methods again, that includes getServerSideProps, getStaticProps, and getInitialProps.

You'll receive the updated pathname and the query via the router object (added by useRouter or withRouter), without losing state.

To enable shallow routing, set the shallow option to true.


Applied to your example:

// pages/[index].js

import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function Index() {
  const router = useRouter()

  return (
    <>
      <a onClick={() => router.push('/?value=1', undefined, { shallow: true })}>
        Value 1
      </a>

      <a onClick={() => router.push('/?value=2', undefined, { shallow: true })}>
        Value 2
      </a>

      <p> {router.query.value} <p>
    </>
  )
}

Upvotes: 1

Related Questions