How do I reload a page with react-router?

JavascriptReactjsReact RouterElectron

Javascript Problem Overview


I can see in this file (https://github.com/ReactTraining/react-router/blob/v0.13.3/modules/createRouter.js) that there is a refresh function but I have no idea how to call it. I'm fairly new to react-router, I've only used it to move between some pages a couple times using hashHistory.

Right now I am trying to use it so that when an install fails, the user is given the option to 'retry' which I plan to execute by refreshing the page where the install happens (the page the user would be currently on). Any help would be appreciated.

This is a node app that runs on electron, not a web app.

Javascript Solutions


Solution 1 - Javascript

firstly, add react-router as a dependency

`yarn add react-router` or `npm install react-router`

import { useHistory } from 'react-router'

const history = useHistory()

/////then add this to the function that is called for re-rendering

history.go(0)

This causes your page to re-render automatically

Solution 2 - Javascript

You can use this to refresh Current route:

import createHistory from 'history/createBrowserHistory'
const history = createHistory();
history.go(0)

Solution 3 - Javascript

You don't really need react-router for this. You can just use location.reload:

location.reload();

Also that version of react-router you linked to is very old, I think it's linking to v1 when it's currently on v4.

Solution 4 - Javascript

I guess that you're using react-router. I'll copy my answer from another post. So you have few possibilities to do that, currently my favorite way to do that is using anonymous function in component prop:

<Switch>
  <Route exact path="/" component={()=><HomeContainer/>} />
  <Route exact path="/file/:itemPath/:refHash" component={()=><File/>} />
  <Route exact path="/:folderName" component ={()=><Folder/>}/>
</Switch>

Or if you want to refresh with current url params, you'll need extra route (reload), and play a little with router stack:

reload = ()=>{
 const current = props.location.pathname;
 this.props.history.replace(`/reload`);
    setTimeout(() => {
      this.props.history.replace(current);
    });
}

<Switch>
  <Route path="/reload" component={null} key="reload" />
  <Route exact path="/" component={HomeContainer} />
  <Route exact path="/file/:itemPath/:refHash" component={File} />
  <Route exact path="/:folderName" component ={Folder}/>
</Switch>

<div onClick={this.reload}>Reload</div>

Solution 5 - Javascript

React

window.location.reload();

working

Solution 6 - Javascript

If you're using react-router v6

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

const navigate = useNavigate();

const refreshPage = () => {
    navigate(0);
}

Solution 7 - Javascript

This solution won't cause the undesired full page reload but requires you to make this modification to each page that needs refreshing:

export const Page = () => {
   const location = useLocation();
   return <PageImpl key={location.key} />
}

So the idea is: create a wrapper around your page and make React re-create the actual page every time the location key changes.

Now it's enough to call history.push(/this-page-route) again and the page refreshes.

Solution 8 - Javascript

I know that this is old, but I found a simple solution according to the documentation of react-router.

Just put that attribute on your Router, and whenever you are on a new Path it will force the page to reload itself.

<Router forceRefresh={true}>

> Source: > https://reactrouter.com/web/api/BrowserRouter/forcerefresh-bool

Solution 9 - Javascript

If you want to use <Link/> to reload some route, or simply have single history push, you can setup <Redirect/> route under <Switch/> like this:

<Switch>
    <Route exact path="/some-route" component={SomeRoute} />
    <Redirect exact from="/some-route/reload" to="/some-route" />
</Switch>

And then <Link to="/some-route/reload" /> or push("/some-route/reload")

Solution 10 - Javascript

If you don't want to reload all scripts again you can replace the current path with a fake/empty path and replace it again with the current path like this

// ...
let currentPath = window.location.pathname;
history.replace('/your-empty-route');
setTimeout(() => {
    history.replace(currentPath)
}, 0)
// ...

Update:

If the changing of the address bar bothering, you can add a patterned route like this:

<Route path="/*/reload" component={null}/>

and add /replace to the end of currentPath to replace the router with null component. like this:

// ...
let currentPath = window.location.pathname;
history.replace(`${currentPath}/replace`);
setTimeout(() => {
    history.replace(currentPath)
}, 0)
// ...

In this way, the reload keyword will add to the end of your current path and I think it's more user friendly.

Notice: If you already have a route that ends with replace It will cause conflict. To solve that you should change the path of the patterned route to something else.

Solution 11 - Javascript

if you want to re-fetch the data just do the below:

import { useLocation } from 'react-router'

const location = useLocation()

useEffect(() => {
  fetchData()
}, [location.key])

Solution 12 - Javascript

You could try this workaround:

// I just wanted to reload a /messages page
history.pushState(null, '/');
history.pushState(null, '/messages');

Solution 13 - Javascript

May be you are trying to push in history object, then bind your component with withrouter or use window.location.href = url to redirect ..

Solution 14 - Javascript

You can use this function.

function reloadPage(){ 
    window.location.reload(); 
}

<input type="button" onClick={ reloadPage }  value="reload"/>

Solution 15 - Javascript

update webpacker.yml

  devServer: {
    historyApiFallback: true,
  }

Solution 16 - Javascript

Well, the easiest way is to first identify a route for reload and thereafter call the window.location.reload() function on the route like so:

<Switch>
  <Route exact exact path="/" component={SomeComponent} />
  <Route path="/reload" render= {(props)=>window.location.reload()} />
</Switch>

Solution 17 - Javascript

If you are needing an asynchronous reload, use history.go(0) (it wraps the History.go() method).

If you need to reload the page synchronously, use history.push(location.pathname) (it wraps the History.pushState() method).

Since there are already examples here using history.go(0), here's an example using history.push(location.pathname):

import React from 'react';
import { useHistory, useLocation } from 'react-router-dom';

const Component = () => {
  const history = useHistory();
  const location = useLocation();

  const reload = () => {
    history.push(location.pathname);
  };

  return (
    ...
  );
};

Solution 18 - Javascript

I recently had the same problem and created this(https://github.com/skt-t1-byungi/react-router-refreshable).

<Refreshable>
    <Switch>
        <Route path="/home">
            <HomePage />
        </Route>
        <Route path="/post">
            <PostPage />
        </Route>
        {/* ... */}
    </Switch>
</Refreshable>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSheriffView Question on Stackoverflow
Solution 1 - JavascriptsambaliciousView Answer on Stackoverflow
Solution 2 - JavascriptSumit KumarView Answer on Stackoverflow
Solution 3 - JavascriptAustin GrecoView Answer on Stackoverflow
Solution 4 - JavascriptDarko PranjicView Answer on Stackoverflow
Solution 5 - JavascriptahmetsadriView Answer on Stackoverflow
Solution 6 - JavascriptDako JuniorView Answer on Stackoverflow
Solution 7 - JavascriptMonsignorView Answer on Stackoverflow
Solution 8 - JavascripthorhorouView Answer on Stackoverflow
Solution 9 - JavascriptGintaras VolkvičiusView Answer on Stackoverflow
Solution 10 - JavascriptBehnam AzimiView Answer on Stackoverflow
Solution 11 - JavascriptSaimumIslam27View Answer on Stackoverflow
Solution 12 - JavascriptAlessander FrançaView Answer on Stackoverflow
Solution 13 - JavascriptNavnath AdsulView Answer on Stackoverflow
Solution 14 - JavascriptHasip TimurtasView Answer on Stackoverflow
Solution 15 - Javascriptdeepak raghuwanshiView Answer on Stackoverflow
Solution 16 - JavascriptKevin KiwangoView Answer on Stackoverflow
Solution 17 - JavascriptaubundyView Answer on Stackoverflow
Solution 18 - JavascriptbyungiView Answer on Stackoverflow