Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change component with react-router without changing URL in address bar?

I am having one use case.

My main react application (container) is loading (mounting) another react child application (module), which is implemented using react-router.

When the route changes in the child application, it is also changing the main application URL.

Is there any way to change the route without changing URL?

I know this is possible without react-router in the child application, by just changing component based on state.

But how can we achieve the same with react-router?

It should be kind of head less application, please help your thoughts.

like image 916
user7175350 Avatar asked Sep 18 '25 23:09

user7175350


1 Answers

If you want to use react-router without changing the URL you may consider using a MemoryRouter

import { MemoryRouter } from 'react-router';
<MemoryRouter>
     <div>
       <Route path="/first" component={FirstComponent} />
       <Route path="/second" component={SecondComponent} />
     </div>
 </MemoryRouter>

And use it like usual:

this.props.history.push('/second')}

A router that keeps the history of your "URL" in memory (does not read or write to the address bar). Useful in tests and non-browser environments like React Native.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/MemoryRouter.md

You just need to be aware that MemoryRouter does not change the browser history, thus you won't be able to press the back button. If you want to keep a back button, you will need to handle it manually.

this.props.history.goBack() // when a user click on the back button
this.props.history.goForward() // when a user click the forward button
like image 122
R.Duteil Avatar answered Sep 20 '25 13:09

R.Duteil