history.push is only changing the URL, not rendering component – React fix

This is one of the common issues caused while configuring react routing. I assume that you added the history object to your router using createBrowserHistory and still getting this issue. Here, I will explain how to fix this issue of history. Consider the below one as your router component.

import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import Login from './login';
import Dashboard from './dashboard';


const Routes = () => {
    const history = createBrowserHistory();
        return (
            <div>
                <Router history={history}>
                    <Route path="/login" component={Login} />
                    <Route path="/home" component={Dashboard} />
                </Router>
            </div>
        );
    }

export default Routes;

If you configure the router component like the above example and try to access history.push or props.history.push from any component, you may face the issue of not rendering the component while changing the URL. You can fix this by importing Router directly from react-router-dom instead of importing BrowserRouter as Router. You can find the corrected code below.

import React from 'react';
import { Router, Route } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import Login from './login';
import Dashboard from './dashboard';


const Routes = () => {
    const history = createBrowserHistory();
        return (
            <div>
                <Router history={history}>
                    <Route path="/login" component={Login} />
                    <Route path="/home" component={Dashboard} />
                </Router>
            </div>
        );
    }

export default Routes;

If the above solution doesn’t work, update react-router-dom to the latest version and try again. This will definitely solve the issue.

Similar Posts

Leave a Reply