Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigate with javascript using the MemoryRouter in react-router

I'm building a single page web application using React. For this application, I'd like to prevent the URL from changing and also avoid using href links to prevent the "link preview" from showing up in the bottom left hand corner of browsers.

To address the first half of my problem I found that using MemoryRouter from react-router prevented URLs from changing when navigating within the application.

Here's a PoC for the router:

import App from './stuff/main/App';
import {Route, MemoryRouter} from "react-router";
import default_page from "./stuff/pages/default_page"
import another_page from "./stuff/pages/another_page"

const app = document.getElementById('root');
ReactDOM.render(
     <MemoryRouter>
       <App>
         <Route exact path="/" component={default_page} />
         <Route path="/anotherpage" component={another_page} />
       </App>
     </MemoryRouter>,
     app
);

Then in App I have code like this (which works):

...
<Link to="/">default_page</Link>
<Link to="/anotherpage">another_page</Link>
{this.props.children}
...

I cannot figure out how to change pages in javascript using the MemoryRouter. The only method I've been able to find that works is using the Link tag, which causes the url to show up on the bottom left hand of the screen. If I could use another element and onclick, I'd be golden.

like image 665
Corey Avatar asked Jul 16 '17 01:07

Corey


1 Answers

If you are in child Component of <Route>, you should have history prop available:

<button onClick={()=>this.props.history.push('/anotherpage')} >another_page</button>

If you are not, you can pass props.history from parent element.

Or if you are deep in structure you should use withRouter HOC

Or you can create a new without path prop, so it will match always and it provide you the right history object.

<Route render={({history})=>(
  <button onClick={()=>history.push('/anotherpage')} >another_page</button>
  // more buttons
)} />
like image 69
Melounek Avatar answered Oct 20 '22 15:10

Melounek