How to handle specific route address in react.js

Viewed 77

I have a specific route like:

http://localhost:3000/Transaction?Authority=A00000000000000000000000000111&Status=NOK

But I don't know how to handle this url, here I used:

        <Route path="/Transaction/:Authority/:Status" element={<Cart />} />

When I entered this URL, it won't redirect me to the Cart component. Why and how can I fix it?

1 Answers

For a URL path such as: "/Transaction?Authority=A00000000000000000000000000111&Status=NOK"

There is only a single path segment and two queryString params. An example Route may look as follows:

<Route path="/Transaction" element={<Cart />} />

The queryString params can be accessed within the Cart component via the useSearchParams hook

const { useSearchParams } from 'react-router-dom';

...

const [searchParams] = useSearchParams();

const authority = searchParams.get("Authority"); // "A00000000000000000000000000111"
const status = searchParams.get("Status");       // "NOK"

If you instead are really wanting to use path="/Transaction/:Authority/:Status" then you should compose your link a little differently

`"/Transaction/A00000000000000000000000000111/NOK"`

const { useParams } from 'react-router-dom';

...

const { Authority, Status } = useParams();

then use the useParams hook to access the route match params

Related