5

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

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for a detail answer!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.