I have a React website with a navbar and want it to appear only on the home page and possibly one other page. I have tried using Switch and also creating a js file called NoNavbar and routing from there but could not get either to work. I am not sure what code to include here but this is the App.js
import Navbar from './Navbar';
import BlackWhite from './pages/BlackWhite';
import Home from './pages/Home';
import Color from './pages/Color';
import { Route, Routes } from 'react-router-dom';
function App() {
return (
<>
<Navbar />
<div className="container">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/BlackWhite" element={<BlackWhite />} />
<Route path="/Color" element={<Color />} />
</Routes>
</div>
</>
);
}
You can create a state to show and hide navbar. set default to true and pass it as prop to the component in which you want to hide navbar and before rendering page set navbar to false.
App.jsx
import Navbar from './Navbar';
import BlackWhite from './pages/BlackWhite';
import Home from './pages/Home';
import Color from './pages/Color';
import { Route, Routes } from 'react-router-dom';
import { useState } from 'react';
function App() {
const [showNavbar, setShowNavbar] = useState(true);
return (
<>
{showNavbar && <Navbar />}
<div className="container">
<Routes>
<Route path="/" element={<Home setShowNavbar={setShowNavbar} />} />
{/* If you want to hide navbar on Blackwhite page then pass the setShowNabar as props */}
<Route path="/BlackWhite" element={<BlackWhite setShowNavbar={setShowNavbar} />} />
<Route path="/Color" element={<Color />} />
</Routes>
</div>
</>
);
}
export default App;
BlackWhite.jsx
import { useNavigate } from 'react-router';
import { BiX } from 'react-icons/bi';
import { useLayoutEffect } from 'react';
export default function BlackWhite({ setShowNavbar }) {
const navigate = useNavigate();
const handleClick = () => {
navigate('/');
};
// Receive setShowNavbar as props and set it to false
useLayoutEffect(() => {
setShowNavbar(false);
}, [])
return (
<div className="BlackWhite">
<h1>Black and white</h1>
{/* <button onClick={handleClick}>Back to homepage</button> */}
<BiX className='icon' onClick={handleClick} />
</div>
);
}
Home.jsx
import { useLayoutEffect } from 'react'
export default function Home({ setShowNavbar }) {
console.log("Home")
// Receive setShowNavbar as props and set it to true
useLayoutEffect(() => {
setShowNavbar(true);
}, [])
return (
<div>Home</div>
)
}
You can add Navbar to your Component in Which you want to show otherwise don't add.
For example - You can add <Navbar />
to <Home />
and don't add to <BlackWhite />
component.