Can I use React-Router-Dom useParams() to capture a coupon code in a MERN Application?

35
November 26, 2020, at 07:10 AM

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?

Answer 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

Answer 2

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

READ ALSO
How to capture matching count value in an array?

How to capture matching count value in an array?

I have an array x which can have following values:

33
Js: Refresh and Acess Token logic [closed]

Js: Refresh and Acess Token logic [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post

43
How to format data to correctly decrypt hex strings in CryptoJS

How to format data to correctly decrypt hex strings in CryptoJS

I have a TCP server that is receiving information via direct IPI am receiving this information encrypted in AES-128-CBC

50