How can I hide component (Navbar) on landing page

Viewed 223

How can I hide the navbar on my landing page('/')? I have tried using this.props.location and extending the navbar component and that dose not seem to work. I know this is simple but I can not for the life of me remember how to do it! I would rather not render the component just on the pages that I want to display it.

App.js

import React from 'react'
import Navbar from './Components/Navbar'
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Home from './Components/Home'
import Welcome from './Components/Welcome'
import About from './Components/About'
import Contact from './Components/Contact'


    function App() {
  return (
    <>
    <useLocation> 
      {({ useLocation }) => { 
        if (useLocation.pathname !== "/") { return <Navbar/>; } }
      } 
    </useLocation>
    <Router>
      <Route exact path="/" component={Welcome}/>
      <Route path="/Home" component={Home}/>
      <Route path="/About" component={About}/>
      <Route path='/Whitepaper' component={WhitePaper}/>
    </Router>
    </>
  );
}

export default App;

Navbar.js

import React from 'react';
import { Link } from 'react-router-dom';
import "../Component Stylesheets/Navbar.css"

const Navbar = (props) =>{
        return(
            <>
                <nav className='navbar'>
                <Link to="/Home">
                    <div className="logo"></div>
                </Link>
                <Link to="/Home">
                    <li className="nav-item nav-link">Home</li>
                </Link>
                <Link to="/About">
                    <li className="nav-item nav-link">About</li>
                </Link>
                <Link to="/Contact">
                    <li className="nav-item nav-link">Contact</li>
                </Link>
                </nav>
            </>
        )
    }
    
 

export default Navbar
2 Answers

You can check what page it is and show it then. I think you mentioned trying this but you just might have been doing it the wrong way.

{props.location.pathname !== '/' ? <Navbar /> : null}

you need to import Location from your react-router.

And use the Location data before your <Router> block. Below is a sample from other react router library which should work same way for react-router as well:

<Location> 
  {({ location }) => { 
      if (location.pathname !== "/") { return <NavBar/>; } }
  } 
</Location>

or you can make use of useLocation Hooks like below to get the current path and exclude NavBar component let location = useLocation();


Related