Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i prevent reloading the whole page? I don't want to reload the Navbar, only load the components inside using react-router-dom

How can i prevent the whole page/Navbar from reloading, i just want to load the components inside without reloading the whole page. I’ve mentioned both the components below.

App.js

import { useState } from 'react';
import Navbar from './Navbar'
import {BrowserRouter as Router, Routes, Route} from "react-router-dom"; 
import Home from './Home';
import ToDoList from './ToDoList';
import Jobs from './Jobs';

const App = () => {


return(
  <>
    <Router>
      <Navbar />
        <Routes>
        <Route path='/' element={<Home />}/>
        <Route path= '/todolist' element={<ToDoList />}/>
        <Route path= '/jobs' element={<Jobs/>}/>
      </Routes>
    </Router>
  </>
)

}
export default App

Navbar.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Navbar = () => {

    return(
        <nav>
            <ul>
            <a href="/"></a>
            <li>
            <a href="/todolist">ToDoList!</a>
            </li>
            <li>
            <a href="/jobs">Jobs</a>
            </li>
            </ul>
        </nav>
    )
}
export default Navbar

>Solution :

Navbar will not rerender with your approach as it’s above the router. So only Router component will be rendered for any change.
But issue here is you are using a tag which should not be used here as React is SPA you need to use <link to="/url">Text</link> Doc

So in Navbar.js just change your a tag to link with appropriate props and it will not rerender. Unless Parent component is going to rerender.

import {Link} from "react-router-dom";
const Navbar = () => {

    return(
        <nav>
            <ul>
            <link to="/"></link>
            <li>
            <link to="/todolist">ToDoList!</link>
            </li>
            <li>
            <link to="/jobs">Jobs</link>
            </li>
            </ul>
        </nav>
    )
}
export default Navbar
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading