Search code examples
reactjsreact-router-dom

How to stop reload the entire project when change from one route to another


When go to page from focused page to all inbox page from by history.push("/Allinbox") the entire application is loading.

I want that its goes from one route to another without refreshing the project.

This is how my routes are:

App.js

<Router history={history}>
  <Switch>
    <Route exact path="/AllInbox" component={AllInboxPage} />
    <Route exact path="/Focused" component={FocusedPage} />
  </Switch>
</Router>

Navigation.js

if (PageName == "/AllInbox") {
  history.push("/AllInbox");
}

if (PageName == "/Focused") {
  history.push("/Focused");
}

AllInbox.js

return (
  <>
    <div className='lefter'>
      <Navigation menupage="/AllInbox" MenuID={MenuID} />
    </div>
  </>
)

FocusedPage.js

return (
  <>
    <div className='lefter'>
      <Navigation menupage="/Focused" MenuID={MenuID} />
    </div>
  </>
)

enter image description here

Like this is my side bar (left panel) if I go from Focused page to AllInbox page then the side bar is loading, I want that when user switch from one page to another page it should change page and need to prevent loading.


Solution

  • For React-router-V5: simply place the <Navigation/> component inside <Router/>. I have not added import statements, please add them wherever necessary.

    App.js:

    export default function App() {
      return (
        <div className="App">
          <Router history={history}>
            <Navigation />
            <div className="main-content">            
                <Switch>
                  <Route exact path="/AllInbox" component={AllInboxPage} />
                  <Route exact path="/Focused" component={FocusedPage} />
                  <Redirect from="*" to="/Focused" />
                </Switch>
            </div>
          </Router>
        </div>
      );
    }
    

    For react-router v6: I suggest you use <BrowserRouter> and <Routes> instead of <Router> and <Switch> and try to use the latest version whenever possible.BrowserRouter handles the history automatically. Now, what you need is a home or index component and inside that you load other components as needed. Sidebar and/or header/footer will be inside home component, they will not be reloaded. Only content is replaced where <Outlet /> is, based on the path chosen. App.js:

    export default function App(){
    return(
    <BrowserRouter>
      <Routes/>
        <Route path="/" element={ <Home /> }>
          <Route index element={<AllInboxes/>} />    
          <Route path="AllInbox" element={ <AllIboxes />} />
          <Route path="Focused" element={<FocusedPage />} />
        </Route>
      </Routes>
    </BrowserRouter>
    );
    

    Home.js

    export default function Home(){
      return(
        <>
          <Sidebar />
          <Outlet/>
          <Footer/>
        </>
      );
    }