As a beginner in react, I'm facing an issue with preventing components from re-rendering when navigating to a different page. Specifically, I want to display only text on my Signup and Login pages, but the Navbar keeps re-rendering every time I switch between links.
I have tried various configurations for react-router v6, but no matter what I do, the Navbar continues to appear below whenever I navigate. The strange part is that I haven't included the Navbar as a Route in my code, yet it shows up along with my image slider created using react-bootstrap carousel.
Here is a snippet of my App.js:
import React from 'react';
import Navbar from './Components/Navbar/Navbar';
import ImageSlider from './Components/Slideshow/ImageSlider';
import {BrowserRouter as Router, Route, Routes, Switch} from 'react-router-dom';
import Signup from './Components/Navbar/Signup';
import Login from './Components/Navbar/Login';
import './App.css';
function App() {
return (
<div className="App">
<Router>
<Navbar></Navbar>
<Routes>
<Route path='/Signup' element={<Signup />}></Route>
<Route path='/Login' element={<Login />}></Route>
</Routes>
</Router>
<ImageSlider></ImageSlider>
</div>
);
}
export default App;
In the above snippet, you can see how the Navbar component is being rendered even though it's not specified as a route. This behavior is causing frustration as it disrupts the intended layout of the pages.
If we take a look at the Navbar.js code:
import React from 'react';
import { MenuItems } from "./MenuItems";
import {Link,NavLink} from "react-router-dom";
class Navbar extends React.Component {
render() {
return(
<nav className="NavbarItems">
<ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>
{MenuItems.map((item,index) => {
return (
<li key={index}>
<NavLink to={item.url} activeClassName="is-active" className={item.cName} style={{position: 'relative', right: 0, top: 13}}>
{item.title}
</NavLink>
</li>
)
})}
</ul>
</nav>
)
}
}
export default Navbar
The Navbar component renders a list of MenuItems which are meant to be navigation links. However, due to the unexpected re-rendering behavior, these links keep appearing even though they shouldn't be displayed when moving to the Signup or Login pages.
This issue also affects the ImageSlider component:
import React from 'react';
import "bootstrap/dist/css/bootstrap.css";
import Carousel from 'react-bootstrap/Carousel';
export default function ImageSlider() {
return (
<div className='slideshow' style={{ height:120}}>
<Carousel controls={false}>
// Code for carousel items...
</Carousel>
</div>
);
}
The ImageSlider is designed to showcase a slideshow with images, but the continuous re-rendering causes disruptions in its presentation as well.