Home > Software design >  How to pass and use query parameters through react router?
How to pass and use query parameters through react router?

Time:01-03

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>
    </>
  );
};

CodePudding user response:

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>
     </>
   );
 };

CodePudding user response:

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

CodePudding user response:

you can send your desire data through location state, and catch it in the new page (where you are redirecting) by the location hook, like this:

<Link to={{pathname: "/sub-cars", state: {carDetails: yourValue}}} 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>

and now on the other side

    import {useLocation} from 'react-router-dom';

     your function {
     const location = useLocation();
      
     const [car, setCar] = useState(location.state.carDetails)

}
  • Related