Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Without Changing URL

I need to have routing that works without changing the URL.

Before implementing this on my own, I tried to look for something by react router. I saw that there is such a thing called createMemoryHistory:

createMemoryHistory([options])

createMemoryHistory creates an in-memory history object that does not interact with the browser URL. This is useful for when you need to customize the history object used for server-side rendering, for automated testing, or for when you do not want to manipulate the browser URL, such as when your application is embedded in an iframe.

But beyond this paragraph there aren't any usage examples and I can't find a usage for this anywhere, i.e: how to use Link component to navigate without a pathname, by which parameter do I route if not pathname, etc.

Is this right for my needs, or do I have to implement a router on my own?

like image 425
Omri Aharon Avatar asked Sep 27 '16 10:09

Omri Aharon


People also ask

How do I use react router without changing URL?

To use React Router without changing the URL, we can use the MemoryRouter component. to import the MemoryRouter component and then wrap it around App to let us navigate with React Router without changing URLs.

Does react router change URL?

The react-router-dom package is great for rendering different React components based on the url path. Therefore, React components can lead to others by changing the url path.

How do I restrict direct URL access in react JS?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?


2 Answers

MemoryHistory is a "history provider", which you can supply to React Router like this:

const memoryHistory = createMemoryHistory(options);

// In your Router configuration
<Router history={memoryHistory} routes={routes} />

Beyond the initial configuration, everything else should work exactly the same as with regular browser history.

This article describes how to use different providers with React Router: Histories

like image 189
mdziekon Avatar answered Sep 30 '22 15:09

mdziekon


React Router 4 has a MemoryRouter

import { MemoryRouter } from 'react-router'

<MemoryRouter>
  <App/>
</MemoryRouter>

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://reacttraining.com/react-router/web/api/MemoryRouter

like image 26
Alasdair McLeay Avatar answered Sep 30 '22 17:09

Alasdair McLeay