Home > OS >  How to hide a component whilst a path is active in react.js?
How to hide a component whilst a path is active in react.js?

Time:01-25

I was trying to implement the following functionality in my web app: Some components in my App.js should be hidden once a path is active as per below:

import './App.css';
import { Route, Routes, Link, Redirect, Navigate } from "react-router-dom";
import { useEffect, useState } from 'react';
import SearchBar from "./components/searchBar";
import Main from './components/main';
import Login from './components/login';
import Register from './components/register';

function App() {




  return (
    <div className="App">
      <nav className="navbar">
        <div className="logo"><img src='https://cdn-icons-png.flaticon.com/512/201/201623.png' /></div>
        <h1 className="title">Travel.com</h1>
        <ul className='menu'>
          <li className="link"><Link style={{ textDecoration: "none", color: "white" }} to='/login'>Log-in</Link></li>
          <li className="link"><Link style={{ textDecoration: "none", color: "white" }} to='/register'>Register</Link></li>
        </ul>
      </nav>
      {
        <Routes>
          <Route path='/login' element={<Login />}></Route>
          <Route path='/register' element={<Register />}></Route>
        </Routes>
      }
      <SearchBar className='search-compon' />
      <Main className='content' />

    </div>

I would like to hide the SearchBar component and the Main component whilst the path of either /login or /register is active.

How to do that ?

CodePudding user response:

You can do this by using a useEffect that evaluates the path and sets a useState variable accordingly.

const [isActive, setIsActive] = useState(false);

useEffect(() => {
    if (
        window.location.pathname == '/login' ||
        window.location.pathname == '/register'
    ) {
        setIsActive(true);
    }
}, []);

But this will only work if you start in one of the paths meaning you don't get there from pressing one of the buttons but by searching the specific link. You can apply the effect to the links as well by adding an onClick event.

<Link
    style={{
        textDecoration: 'none',
        color: 'white',
    }}
    to='/login'
    onClick={() => setIsActive(true)}
>
    Log-in
</Link>

Now the state changes bo matter how you reach the path, now we just need to make some conditional rendering for the two components. this can be done like:

{!isActive && (
    <>
        <SearchBar />
        <Main />
    </>
)}

And now it should all work!

  • Related