Skip to content Skip to sidebar Skip to footer

React History.push() Not Rendering New Component

I have a React.js project with a simple sign in function. After the user is authorized, I call history.push method which changes the link in the address bar but does not render the

Solution 1:

If anyone is interested - this was happening because the app was rendering before the history was pushed. When I put the history push into my action but just before the result is converted into JSON, it started working since now it pushes history and only then renders the App.

exportconstauthorization = (username, password, history) => (dispatch) =>newPromise ((resolve, reject) => {
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password,
      })
    }).then( response => {
      if (response.ok) {

          //################################//This is where I put it

          history.push("/servers");

          //################################

          response.json().then( result => {
            dispatch(logUserIn(result.token));
            resolve(result);
        })
      } else {
        let error = newError(response.statusText)
        error.response = response
        dispatch(showError(error.response.statusText), () => {throw error})
        reject(error);
      }
    });
  });

Solution 2:

You need to apply withRouter to use this.props.history.push('/page') in every component that use "push"

import { withRouter } from'react-router-dom';
.....
exportdefaultwithRouter(MoneyExchange);

this is important when using push.

Solution 3:

First, create a history object used the history package:

// src/history.js
import { createBrowserHistory } from'history';
export defaultcreateBrowserHistory();

Then wrap it in in Main Router Component.

import { Router, Route, Link } from'react-router-dom';
    import history from'./history';

    ReactDOM.render(
        <Providerstore={store}><Routerhistory={history}><Fragment><Header /><Switch><SecureRouteexactpath="/"component={HomePage} /><Routeexactpath={LOGIN_PAGE}component={LoginPage} /><Routeexactpath={ERROR_PAGE}component={ErrorPage} /></Switch><Footer /></Fragment></Router></Provider>)         

Here, After dispatching the request, redirecting to home page.

functionrequestItemProcess(value) {
        return(dispatch) => {
            dispatch(request(value));
            history.push('/');
        };

    }   

should be helpful :)

Solution 4:

Try to use custom history and Router instead of BrowserRouter. After installing history:

yarn add history

Create a custom browser history:

import { createBrowserHistory } from "history";

exportdefaultcreateBrowserHistory();

Use Router instead of BrowserRouter in your setup:

import history from"your_history_file";

ReactDOM.render(
  <Providerstore={createStore(mainReducer,applyMiddleware(thunk))}><Routerhistory={history}><Main /></Router></Provider>,
  document.getElementById('root')
);

or if you don't want to use a custom history file and import from there you can crate it directly in your index.js:

import { createBrowserHistory } from"history";

const history = createBrowserHistory();

ReactDOM.render(
  <Providerstore={createStore(mainReducer,applyMiddleware(thunk))}><Routerhistory={history}><Main /></Router></Provider>,
  document.getElementById('root')
);

Solution 5:

I using react-electron-boilerplate and i experienced a issue using MemoryRouter

using history.push('/someUrl') doesn't work...

Just use exact property in component, and initialEntries to set your default route.

<RouterinitialEntries={['/']}><Switch><Routeexactpath="/"component={LoginScreen} /><Routeexactpath="/session"component={SessionScreen} /></Switch></Router>

Post a Comment for "React History.push() Not Rendering New Component"