0

I have been trying to figure out to how to capture a coupon code using react-router-dom's URL Parameters. I was hoping to be able to capture a coupon in the URL to set a state.

Example: https://localhost:3000/checkout?coupon=FREE3000&referrer=MATTHEW;

I want to be able to parse the URL to take the parameters Coupon & Referrer to set in the state, and to prefill a form in a checkout page.

Is this possible using React Router Dom? Are there any alternative solutions?

2 Answers2

1

The short answer is no, useParams gets the parameters after the base url not the query parameters.

For an answer on how to get the query parameters see this question How to get query parameters in react-router v4

Shmili Breuer
  • 3,284
  • 16
  • 19
1

Yes this is possible via react router with a custom hook and the useLocation hook. Anyways you will use URLSearchParams. There is no direct function from react router.

const useQuery = () => new URLSearchParams(useLocation().search)

// use in component
const query = useQuery();

// get desired value with query.get(name)
const coupon = query.get("coupon");
const referrer = query.get("referrer");

Refer to this example from the react router docs

If you want to not use react router simply use the window.location.search property instead of useLocation. See the MDN documentation

Julian Kleine
  • 1,251
  • 4
  • 13