Can hash routes be defined in next.js?

Previously, I created a modal component using <HashRouter> in react-router where the modal would become active or inactive based on the hash url. For example, the modal is inactive when the url is /route, but becomes active when the url is /route#modal1. Is there any method to define hash routes in next.js?

Answer №1

When dealing with URLs, it's important to note that the hash symbol portion (which identifies an HTML entity) is not transmitted to the server. This means that you won't be able to match the URL serverside if a browser loads something like /route#modal1 - the server will only see /route. However, there are ways to work around this:

Option 1: Manage modal rendering on the client side using next/router in your component. Here's a sample code snippet assuming you're working with class components:

import Router from 'next/router'

....

componentDidMount(){
  let id = Router.asPath.match(/#([a-z0-9]+)/gi )
  if(id){
    // show the modal
  }else{
    // do something else
  }
}

Option 2: Pass the ID to the URL without the #. In your server.js, add a route similar to the following:

server.get('/route/:id?', (req, res) => {
  let {id} = req.params 
  return app.render(req, res, '/mypage', { id })
})

Then extract the ID, for example in getInitialProps:

static async getInitialProps (context) {
  let ctx  = context.query;
  return ctx
}

You can then handle the modal accordingly:

componentDidMount(){
  let {id} = this.props    
  if(id){
    // show the modal
  }else{
    // do something else
  }
}

Answer №2

If you want to achieve this functionality, you can utilize the next/router.

For example, we implement hash routing on a specific page to display different components based on the hash URL. This allows users to navigate back and forth using standard web navigation buttons.

// page.js

export default function MyPage() {
  const router = useRouter();
  const hash = router.asPath.split('#')[1] || '';
  const showModal = hash === 'modal1' ? true : false;
  const openModal = () => {
    router.push({ hash: 'modal1' });
  }  
  return (
    <>
      <h1>MyPage</h1>
      <Button onClick={openModal}>Open Modal 🙂</Button>
      {showModal && <ModalOne />}
    </>
  )
}
// ModalOne.js

export default function ModelOne {
  const router = useRouter();
  const closeModal = () => {
    router.push({ hash: '' });
  }
  return (
    <>
        <h1>Hello Modal</h1>
        <Button onClick={closeModal}>Close Modal 🙃</Button>
    </>
  )
}

Whenever the router hash changes, a re-render occurs, allowing the modal to open similarly to how it would in a single-page application.

This setup also ensures that the modal closes when the user navigates back on a mobile device, aligning with our expected behavior for this scenario.

Please note that I am working with nextjs version 12.1.0

Answer №3

To include a hash in the URL, you can utilize the next/router library.

In certain scenarios, I dynamically alter the component being rendered based on a state string. To ensure that I am aware of the current route and maintain functionality of the back button, I append a state string stage as a hash to the URL when a change is detected.

React.useEffect(() => {
  router.push(`/booking#${stage}`)
}, [stage])

Please note that this approach is specifically for client-side operations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

unable to choose just one material ui checkbox

I'm new to using React and I'm currently developing a simple todo app with React JS and Material UI. To accomplish this, I've created two separate components - one for taking user input (TodoInput) and another for rendering each individual t ...

How can you hide all siblings following a button-wrapper and then bring them back into view by clicking on that same button?

On my webpage, I have implemented two buttons - "read more" and "read less", using a Page Builder in WordPress. The goal is to hide all elements on the page after the "Read More" button upon loading. When the button is clicked, the "Read More" button shoul ...

What is the best way to resume a Jquery function if it has not

How do I make my form alert re-trigger when the user clicks the button again if the input is still empty? What I've tried: After clicking the button, it checks if the inputs are empty and shows an alert. However, once the alert appears, if I click th ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

Service workers do not support fetching from .html files

Struggling with creating a functioning service worker for offline use has been a challenge. Despite trying numerous examples, the success has remained elusive. Initially, I suspected that the dynamic nature of my PHP-based website was causing the issue, or ...

Error connecting Node.js, express, and socket.io application

My app is a simple one that utilizes the socket.io module for node.js. Everything runs smoothly when I start my server with the command node express_server.js. However, when I try to open my page at http://localhost:8080 in the browser, Node.js throws an e ...

Encountering a "NextJS Google Drive API error due to Insufficient Permission when using Service

I am currently developing a basic NextJS application with the goal of displaying files from a specific Google Drive folder. The Google Drive folder belongs to my personal account and is shared with a Service Account that I created in Google Cloud Platform ...

Tips for resolving issues related to Nodemailer configuration

I am currently working on a script that sends form data to an email address. I am using Express and Nodemailer with Node.js, but as a beginner, I am struggling to understand why the email authorization stops and prevents the letters from being sent. Here ...

A guide on utilizing a service name as an address to retrieve a dynamic route in next.js

I am facing a challenge where I need to set up a Kubernetes cluster with a NextJS front-end and a service that requires making requests from the front-end to another service within the same cluster using fetch. The issue arises when trying to build the do ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

Private route displaying unexpected behavior when making API call

A snippet of code I have been working on is partially functioning (refer to the last paragraph for a detailed description): App.Js: export default function App() { const [isLoggedIn, setisLoggedIn] = useState(null); const logIn = () => { setisLogg ...

Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortu ...

To avoid the sudden appearance of a div on the screen, React is programmed to wait for the

Struggling with preventing a flashing div in React where the error message renders first, followed by props, and finally the props render. The EventsView component includes the following code: view.js var view; if (_.size(this.props.events) !== 0) { vie ...

"Comparing the similarity and accessibility of using the same browser session with a Firefox or Chrome

I'm working on a solution to close and open the same session in my browser using a Firefox extension. The code I have currently closes the browser and then opens the last session, but it also opens another window which is not desired. I want to be abl ...

By setting up a keydown event listener, I am unable to inspect HTML elements by using the F-12 key shortcut in Chrome

Recently, I encountered an issue where adding a keydown event listener in my JavaScript code prevented F-12 from working properly. window.addEventListener("keydown", function (event) { if (event.defaultPrevented){ retu ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...

When utilizing "Koa-Rewrite," an AssertionError occurs stating that app.use(rewrite) necessitates a generator function

I am currently working with Koa@1 and koa-rewrite@1 to implement a specific functionality. rewritelogic.js const rewrite = require('koa-rewrite'); function rewriteLogic(){ rewrite('/english/experience/dev1', '/english/experienc ...

Struggling with Getting My Animation to Function Correctly

I am trying to create a JQuery Animation that will move a div covering a text box up into the border when clicked. Despite multiple attempts, I can't seem to get the animation to work properly. Any suggestions? JavaScript function moveup(title,text ...