import browserHistory from react-router

16,246

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>;
  )
}
Share:
16,246
Irfan Shaikh
Author by

Irfan Shaikh

An idiot admires complexity, A genius admires simplicity. ⏳

Updated on June 04, 2022

Comments

  • Irfan Shaikh
    Irfan Shaikh almost 2 years

    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
    Irfan Shaikh over 5 years
    i am trying to redirect from one page to another and when i googlr it i found this one browserHistory
  • Irfan Shaikh
    Irfan Shaikh over 5 years
    Why you are using this HomWitRouter it gives me warning like this is defined but it's value never used.
  • Shevchenko Viktor
    Shevchenko Viktor over 5 years
    You need to export HomeWithRouter component and use it. Or use it in this file.