Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Router V4 history.push not working

I have upgraded to React Router V4 and now struggling with the history.push method.

I have an index.js file:

import React from "react"; import { render } from "react-dom"; import { BrowserRouter, Route } from 'react-router-dom'; import createBrowserHistory from 'history/createBrowserHistory';  const history = createBrowserHistory();  import { Main} from "./components/Main"; import { About } from "./components/About"; import { Cars} from "./components/Cars";   class App extends React.Component {  render() {     return (         <BrowserRouter history={history}>              <div>                 <Route path={"/"} component={Main} />                 <Route path={"/cars"} component={Cars}/>                 <Route path={"/about"} component={About}/>             </div>         </BrowserRouter>     )   } }  render(<App/>, window.document.getElementById("app")); 

And then I have another file, where I added a simple to return to a certain page which looks like this:

import React from "react"; import createBrowserHistory from 'history/createBrowserHistory';  const history = createBrowserHistory();  export class Cars extends React.Component {   navigateBack() {     history.push('/')   }    render() {     return(         <div>             <h3>Overview of Cars</h3>             <p>Model: </p>             <button onClick={this.navigateBack} className="btn btn-primary">Back</button>         </div>     )   } } 

So, I cannot figure out whats going wrong here. When I click on the button, the URL changes to / but thats all. Is there someone who can help me out?

EDIT

I found out, that it works when I do this:

this.props.history.push('/home') 

and

<button onClick={this.onNavigateHome.bind(this)} 

but it seems wrong somehow??

when I do

this.context.history.push('/home') 

I get Cannot read property 'context' of null but why?? Is my <BrowserRouter> setup wrong??

Anyway, thanks for the help :)

like image 333
ST80 Avatar asked Apr 07 '17 13:04

ST80


People also ask

How do you push to history in react router v4?

To push to History in React Router v4, we can use the createBrowserHistory method to return the history object. Then we can call push on the history object. import { createBrowserHistory } from 'history'; export default createBrowserHistory();

Does react router use history API?

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.


Video Answer


1 Answers

You have to import {withRouter} from 'react-router-dom' and export your class in this way

export default withRouter(Cars)

like image 131
Steven Daniel Anderson Avatar answered Sep 24 '22 14:09

Steven Daniel Anderson