How to Display Different Navbar Component for Different ReactJS Pages
Displaying different navigation bars for different pages in ReactJS can be achieved by creating multiple navigation components and conditionally rendering them based on the current page or route.
Here’s an example of how you can implement this:
Create the Navigation Components
In your ReactJS project, create separate navigation components for each page. Let’s say you have two pages: Home and About. Create two new components: HomeNavbar
and AboutNavbar
.
{`// HomeNavbar.js
import React from 'react';
const HomeNavbar = () => {
return (
);
};
export default HomeNavbar;
// AboutNavbar.js
import React from 'react';
const AboutNavbar = () => {
return (
);
};
export default AboutNavbar;`}
Conditionally Render the Navigation Components
In your main layout component, which is rendered on every page, import the navigation components and use conditional rendering to render the appropriate navigation component based on the current page or route. You can do this using React Router or any other routing library.
{`// Layout.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import HomeNavbar from './HomeNavbar';
import AboutNavbar from './AboutNavbar';
const Layout = () => {
const currentPath = window.location.pathname;
let navbarComponent;
if (currentPath === '/') {
navbarComponent = ;
} else if (currentPath === '/about') {
navbarComponent = ;
}
return (
{navbarComponent}
{/* Route definitions */}
);
};
export default Layout;`}
In this example, we import the navigation components (HomeNavbar
and AboutNavbar
) and use the window.location.pathname
to get the current page’s path. Based on the current path, we conditionally render the appropriate navigation component.
Remember to define your routes using the <Switch>
and <Route>
components from React Router or any other routing library you are using.
By implementing this logic, you can display different navigation bars for different pages in your ReactJS application.