How to take Url Value In Next Js 14.

There are several ways to retrieve URL values. Sometimes, you only need to extract URL parameters to display data dynamically.

  1. Core Javascript Method
  2. Nextjs Method

This version emphasizes the structure of your explanation and makes it clear which method you’re currently discussing.

Core Javascript Method

In this method, I’ve used the window.location.search JavaScript method, which is a core JavaScript approach.

'use client';
import { useEffect,useState } from "react";
export default function Home() {

  const [params, setparams] = useState('')
  useEffect(() => {
    const paramsValue = window.location.search
    console.log(paramsValue)
    setparams(paramsValue)
  }, [])
  
  return (
    <>
    <div>Hello This Is Param Page</div>
    <div>Parameter value is {params}</div>
    </>
  );
}

In the above method, I’ve implemented a useEffect hook, which executes when the website loads. Within this hook, I’ve created a variable to store the value of the parameters.

Additionally, I’ve utilized the useState hook to initialize an empty state variable for holding the parameter value. This hook allows us to dynamically update the parameter value within the component.

Furthermore, I’ve included the parameter value within an element, enabling it to be displayed in the frontend.

Next.js method

Next.js provides a convenient hook called useSearchParams for fetching parameter values. This method is recommended over using pure JavaScript, as it simplifies the process and aligns with Next.js conventions.

'use client';
import { useSearchParams } from "next/navigation";
export default function Home() {
  const params = useSearchParams();
  console.log(params)
  // Link = http://localhost:3000/home?userid=AdityaKumarAlok
  return (
    <>
      <div>Hello This Is Param Page</div>
      <div>Parameter value is {params.toString()}</div> {/* userid=AdityaKumarAlok */}
      <div>Parameter value is {params.get('userid')}</div> {/* Output = AdityaKumarAlok */}
    </>
  );
}

In this method, I’ve imported the useSearchParam() hook from next/navigation and assigned its return value to the params variable.

To retrieve the entire parameter values, we can use the toString() method, which converts the parameters into a string. Then, we can split the string according to our requirements and use cases.

For fetching a specific value, we can utilize the get() method by providing the key of the parameter we want to fetch.

Leave a Reply

Your email address will not be published. Required fields are marked *