Getting query parameter with hyphen in nextJS 13 - step by step tutorial

One of the challenges I am facing involves accessing a query parameter with a hyphen in its name within a route:

/?previous-page=building-details

Within my Page component:

import EnergyEfficiency from "@/ui/energy-check/energy-efficiency"

const Page = ({
  params,
  searchParams,
}: {
  params: { id: string }
  searchParams: { modernization: string; previousPage: string }
}) => {
  const { modernization, previousPage } = searchParams

  console.log(previousPage) // undefined

  return <EnergyEfficiency addressID={params.id} />
}

export default Page

I'm trying to figure out how to access this specific parameter from the props of the page, any tips on achieving that?

Answer №1

One way to access query parameters from your route is by using the useSearchParams hook.

The useSearchParams hook is a client-side component hook that allows you to retrieve the query string from the current URL.

import { useSearchParams } from 'next/navigation'

export default function Page() {

  const searchParams = useSearchParams()
  
  const previousPage = searchParams.get('previous-page')
  console.log('previousPage', previousPage) // prints 'building-details' to the console

  return (
    <h1>Welcome</h1>
  )
}

If we're discussing a Server Component, here is how it can be implemented:

Note: Make sure to use the app folder as specified below.

You need to create a new contact folder within the app folder, and then add a page.tsx file inside the newly created contact folder with the provided code snippet.

File Structure

https://i.sstatic.net/9dNYf.png

const Page = ({
  searchParams,
}: {
  searchParams: { [key: string]: string | string[] | undefined }
}) => {
    const contactWay = searchParams["contact-way"]
    return (
        <>
            <h1>Contact Page</h1>
            <h2>Contact Way: {contactWay}</h2>
        </>
    )
}

export default Page

Go to http://localhost:3000/contact?contact-way=email to see the result:

https://i.sstatic.net/8NkAV.png

CodeSandbox: https://codesandbox.io/p/sandbox/upbeat-leaf-6scwsm?file=%2Fapp%2Fcontact%2Fpage.tsx%3A3%2C5

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

Having trouble with playing the appended HTML5 Video?

Having trouble getting a video player to display after clicking a button. This is the code I use to add the video player in index.html: $("#videoContainer").append( "<video id=\"video-player\" width=\"100%\" height ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

The CSS and JavaScript in pure form are not functioning properly upon deployment in Django

In my Django project, I am utilizing pure CSS and Bootstrap. Everything appears as expected when I test it on my local machine. However, once deployed, the appearance changes. The font looks different from how it did before deployment: After deploying to ...

Updating an HTML element by using the input value in a text field with JavaScript/jQuery

Although it may seem straightforward, I am new to Javascript and struggling to find or create the script I need. I have a list of BIN numbers for credit cards and want to extract the first 6 digits of the card number field to determine the type of card, an ...

The progress bar for uploading a file is causing issues with the redirect function in the

I am currently facing an issue with my file submission form and progress bar in JavaScript. The progress bar is interfering with the controller, preventing it from redirecting back home with the link. I have tried removing window.location.href="/"; but thi ...

Tips for updating multiple bundled javascript files with webpack

I am working on a straightforward app that requires users to provide specific pieces of information in the following format. Kindly input your domain. User: www.google.com Please provide your vast URL. User: www.vast.xx.com Select a position: a) Bottom ...

Leveraging jQuery to extract a key-value pair and assign it to a new property by

I'm struggling with extracting a value from a key-value pair and inserting it into the rel property of an anchor tag. Even though I try to split the code and place the value correctly, it doesn't seem to work as expected. Instead of applying the ...

Allow images to be uploaded using the browser-policy package in Meteor

Can anyone help me figure out how to use Sir Trevor JS in Meteor for uploading images without encountering this error message? When attempting to load the image 'blob:http%3A//localhost%3A3000/a28ef7dc-ee51-4290-9941-6b8fc317e685', I am receivin ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Greetings! I am looking for information on how to activate CORS in a Ruby on Rails API application deployed on OpenShift for use with an Angular

My current setup involves a script utilizing Angular to display records fetched from a Rails API REST, which is hosted in OpenShift. In my public/.htaccess file, I have included the following directives: Header add Access-Control-Allow-Origin "*" Header a ...

Facing an issue with importing types in Prisma database seeding using TypeScript with the `type:module` configuration

I am currently learning about Prisma and following this tutorial: https://www.prisma.io/blog/fullstack-nextjs-graphql-prisma-oklidw1rhw However, I encountered an issue with the following step: npx prisma db seed --preview-feature Even though I copied the ...

Is it possible to execute the .push() method on an array a specific number of times without using a for loop?

Currently, I am tackling the "Move Zeroes" Leetcode challenge. The task requires moving all zeroes to the end of the array without altering the sequence of non-zero elements. My strategy involves iterating through the array, splicing out each zero encounte ...

What is the process for using the CLI to downgrade an NPM package to a previous minor version by utilizing the tilde version tag?

I currently have Typescript version ^3.7.4 installed as a devDependency in my project's package.json: { "name": "my-awesome-package", "version": "1.0.0", "devDependencies": { "typescript": "^3.7.4" } } My goal is to downgrade Typescript ...

Keyboard control of Material UI Checkbox

As we work on developing a web application using react and material ui, accessibility for persons with disabilities is a key consideration. This means ensuring that the web application is operable through keyboard navigation. It's important that user ...

intl-tel-input's getExtension function is returning a value of 'null'

I've been attempting to retrieve the extension of the mobile number that has been input. All other variables are functioning correctly, but the extension variable is returning a null value. It appears that it is sending a null value to the POST method ...

Having trouble with setting up ENV variables while deploying the app on Heroku

I recently deployed my node.js app to Heroku, and I'm facing some issues with its functionality. The app loads fine, but when I try to sign in, it breaks down. It seems like the environment variables are not loading correctly, specifically the db vari ...

Exclude React Native module and import web module in Webpack

Currently, I am facing a challenge in my project where I need to alias a different package specifically for a webpack configuration. The issue revolves around the VictoryJS library (link: https://formidable.com/open-source/victory/). In my React Native app ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...