Arthur
Arthur

Reputation: 3506

How to render components with query strings React-Router

CodeSandbox — codesandbox

I'm trying to render components with react-router, but I don't understand correctly how to work with query strings. So condition — if ?tbm=first ⟹ it'll render first component and so on. How to do this?

Example:

enter image description here

Upvotes: 5

Views: 3846

Answers (2)

Thomas Hennes
Thomas Hennes

Reputation: 9939

A different query string doesn't form a different path. In your example, the path is always the same, i.e. /search, so routing cannot differentiate between your components.

If you amend your code to have three actual paths (/first, /second and /third) and amend the links accordingly, then your code works as intended, see

If you want to switch on the query string, you have to stick to a single Route with path /search and display your component object based on the parsed querystring, see

Upvotes: 5

JupiterAmy
JupiterAmy

Reputation: 384

The query string will be available inside this.props.location.search inside your rendered component. So the idea is you need to have a parent component which gets rendered something like this.

<Route path="/" component={parentComponent} />

Now whatever you enter as query string will be available and you can see that if you crack open your react dev tool. And once you have this string just parse it and have dynamic routes based on your custom condition. check out image for your reference.enter image description here

Upvotes: 3

Related Questions