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
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