Search code examples
javascriptreactjsbrowser-history

History.push works on BrowserRouter but not Router


So I'm trying to use history.push('/path') in my components. My set up looks like this:

App.js

import { Router, Switch, Route } from 'react-router-dom';

// History
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();

function App() {
  return (  
      <Router history={history}>
            <Switch>
              <Route path='/' exact render={(props) => <Homepage />} />
              <Route path='/search' render={(props) => <SecondComponent />} />
            </Switch>
      </Router>
  );
}
export default App;

SecondComponent.js

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

const SecondComponent = ({ history  }) => {

    const myFunction = () => {
        history.push('/search');
    };

    return (
    <button onClick={() => myFunction}>stuff</button>
    );
}

export default withRouter(SecondComponent);

The problem is that when I click the button the URL changes but the component doesn't render. The thing is if I replace Router in app.js with BrowserRouter it works fine but I get a warning: <BrowserRouter> ignores the history prop. To use a custom history, use import { Router } instead of import { BrowserRouter as Router }.


Solution

  • react-router 5x is compatible with history 4x. Check the history version, and if higher than 4x, try downgrading to 4x version, and it should work fine with Router