Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 771
Arthur Avatar asked Feb 11 '19 16:02

Arthur


2 Answers

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

like image 98
Thomas Hennes Avatar answered Nov 12 '22 15:11

Thomas Hennes


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

like image 32
JupiterAmy Avatar answered Nov 12 '22 14:11

JupiterAmy