Syntax to add dynamic parameter in react js

Viewed 773

I need syntax help here in react js,

I wish to achieve something like this in the path

http://localhost:3000/verify-email?key=ffdffae0237c43e6572bca3a3867eda1&eid=c2Frc2hpN0BnbWFpbC5jb20=

The following code doesn't work

<Route name="businessInformation" exact path="/verify-email?key=:someRandomKey&eid=:someRandomKey"> //Need help here

Although, this works for http://localhost:3000/verify-email/:key/:eid

 <Route name="businessInformation" exact path="/verify-email/key/eid">

How shall I append such string values so that it understands?

2 Answers

Ok, the question is very unclear, for the sake of brevity let's assume that you want to read a query string. The route for this would simply look like:

<Route
    name="businessInformation"
    exact path="/verify-email"
    render={props => <Example {...props}>}
/>

and the component which would need to read the query string would look like:

const Example = () => {
    const { key, eid } =  new URLSearchParams(window.location.search)
    
    return (
        <span>{`key is ${key} and id is ${eid}`}</span>
    )
}

And in case you wanting to navigate to such a route, it would be:

<Link to={`/verify-email?key${key}&eid=${id}`}/>

This is query string

"?var1=val&var2=val2"

And, this is URL parameters

/api/:param1/edit

To achieve query string with dynamic values, I would suggest to use template literats

const someRandomKey = "<random_key>"; // Either hard-code any value or read from a state / props. 
const someRandomId = "<random_id>";
<Route name="businessInformation" exact path=`/verify-email?key=${someRandomKey}&eid=${someRandomKey}`>
Related