2

i'm trying to import browserHistory but i get error something like this.

 ./src/App.js
  Attempted import error: 'browserHistory' is not exported from 'react- 
  router'.

And My Code is:

import React, { Component } from "react";
import { browserHistory } from "react-router";

import App from "./App";
class Home extends Component {
 home = () => {
browserHistory.push("/home");
  };
    state = {};
  render() {
    return <button onClick={this.home} className="btn btn-outline-light">
            Logout
          </button>;
 }

}

Irfan Shaikh
  • 65
  • 1
  • 1
  • 9
  • Which version of React Router? In v4, individual histories were removed and replaced with routers, ie `BrowserRouter` from `"react-router-dom"` – Andrew Li Jan 23 '19 at 12:23
  • This may explain everything https://github.com/ReactTraining/react-router/issues/5263 – Ionut Jan 23 '19 at 12:24
  • Possible duplicate of [Where's hashHistory in React Router v4?](https://stackoverflow.com/questions/46016415/wheres-hashhistory-in-react-router-v4) – Andrew Li Jan 23 '19 at 12:26
  • Possible duplicate of [React router not showing browser history](https://stackoverflow.com/questions/44063229/react-router-not-showing-browser-history) – Ionut Jan 23 '19 at 12:28

1 Answers1

5

As I understand your main intention is to change browser URL in the right way, not actually importing a browserHistory

For react-router v4:

You should benefit here from HOC withRouter. Apply it in next manner, and this will pass into your component some additional props that will allow navigation over browser history

import { withRouter } from "react-router-dom";

class Home extends Component {
   home = () => { 
      // - you can now access this.props.history for navigation
      this.props.history.push("/home");
   };

   render() {
       return ( 
           <button onClick={this.home} className="btn btn-outline-light">
            Logout
          </button>;
       )
}

const HomeWitRouter = withRouter(Home);

And with react-router v5 and React Hooks this may look like:

import { useHistory } from "react-router-dom";

export const Home = () => {
  const history = useHistory();
  const goHome = () => { 
    history.push("/home");
  };

  return ( 
    <button onClick={goHome} className="btn btn-outline-light">
      Logout
    </button>;
  )
}
Shevchenko Viktor
  • 3,300
  • 2
  • 14
  • 21