Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass and use query parameters through react router?

I'm trying to take the value of a query parameter through the url and use it for an api call for example :

import { Link, useSearchParams } from "react-router-dom";

const CommonTypes = () => {
  let [searchParams, setSearchParams] = useSearchParams();

  const handleClick = (car) => {
    setSearchParams({ type: car });
  };

  return (
    <>
      <div className=" w-screen">
        <div className="container mx-auto max-w-5xl px-10 grid grid-cols-2 gap-10 py-10">
          <div className=" min-w-7xl h-fit border rounded-lg border-stone-900 p-5 pb-16 text-left ">
            <h1 className="font-semibold text-xl mb-2 font-sans">
              <span className="text-red-500 font-semibold text-xl font-sans">
                Common
              </span>{" "}
              types of choice
            </h1>
            <p className="font-sans font-medium">
              You can quickly pick a category from here by clicking on one of
              the following icons
            </p>
            <p>
              -----------------------------------------------------------------
            </p>
            <div className="grid grid-cols-3 gap-14 text-center ">
              <Link to={"/sub-cars"} onClick={handleClick(hatchback)}>
                <div className="">
                  <img src={hatchback} alt="" className="w-44 h-28"></img>
                  <p>----------------</p>
                  <span className="font-sans font-semibold text-red-500">
                    HATCHBACK
                  </span>
                </div>
              </Link>

as you can see i'm passing the value type but the url doesn't pass through a query parameter for example : http://localhost:3000/sub-cars?type=hatchback so i can use it within the new page for an api call , my other component looks like this

const Models = () => {
  let [searchParams, setSearchParams] = useSearchParams();

  useEffect(() => {
    console.log("lol");
    console.log(searchParams.get("type"));
  }, []);

  return (
    <>
      <Navbar />
      <span>{searchParams.get("type")}</span>
    </>
  );
};
like image 829
Mohamed Nabil Avatar asked Nov 17 '25 19:11

Mohamed Nabil


2 Answers

I think you are using react router dom v6 , It has some new updates , For navigating user to other page and passing search query you can do something like below , replace like this to link and import createSearchParams from react-router-dom

   <Link
        to={{
          pathname: "sub-cars",
          search: `?${createSearchParams({
            type: "cars"
          })}`
        }}
      >
import { useNavigate, createSearchParams, Link } from "react-router-dom";

export default function Home() {
  const navigate = useNavigate();
  return (
    <div>
      <Link
        to={{
          pathname: "sub-cars",
          search: `?${createSearchParams({
            type: "cars"
          })}`
        }}
      >
        <button>First Method - Take me to Sub Cars</button>
      </Link>

      <br />
      <br />

      <button
        onClick={() => {
          navigate({
            pathname: "sub-cars",
            search: `?${createSearchParams({
              type: "cars"
            })}`
          });
        }}
      >
        Second Method - Take me to Sub Cars
      </button>
    </div>
  );
}

You can check the codesandbox also

Edit admiring-flower-vtohb

like image 74
Goutham J.M Avatar answered Nov 19 '25 09:11

Goutham J.M


I think this is because of useSearchParams in useEffect. try it using outside of the effect and make dependency of the type in effect.

for example..

const Models = () => {
        let [searchParams, setSearchParams] = useSearchParams();
  
    let type = searchParams.get("type")

    useEffect(() => {
      console.log("lol! the type is " , type );
     }, [type ]);

   return (
     <>
       <Navbar />
       <span>{type}</span>
     </>
   );
 };
like image 25
Pankaj Chaturvedi Avatar answered Nov 19 '25 08:11

Pankaj Chaturvedi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!