skip to Main Content
`import './SideNavBar.scss';
import { useState } from 'react';
import { Cancel01Icon, Menu01Icon } from '../assets/icons';
import { Link } from 'react-router-dom';

const SideNavBar = () => {

const [isOpen, setIsOpen] = useState(false);

const toggleMenu = () => setIsOpen(!isOpen);

   return (
  <>
    <button className="menu-button" onClick={toggleMenu}>

     {isOpen ? <Cancel01Icon className='sideicon' /> : <Menu01Icon className='sideicon' />}

    </button>

  <nav className={`side-navbar ${isOpen ? 'open' : ''}`}>
    <ul className='side-navbar-ul'>
      <li className='side-navbar-li'><Link to={'/'}>Home</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><Link to={'/loja'}>Loja</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><Link to={'/galeria'}>Galeria</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><Link to={'/contato'}>Contato</Link></li>
        <div className='line'></div>
      <li className='side-navbar-li'><a>Restrito</a></li>
        <div className='line'></div>
        
      

         </ul>
       </nav>
     </>

     )};

     export default SideNavBar;`

#How could I make this navbar close when I click in out of it, considering that this is a React app? I’ve seen somethings but it’s more like vanila js, I need to know how to do this in a React component, jsx

2

Answers


  1. You can use this hook that I wrote before:

    /**
     * Custom hook that triggers a callback function when a click event occurs outside of a specified element.
     * @param ref - The ref object that represents the element to monitor for click events.
     * @param callback - The callback function will be executed when a click event occurs outside the element.
     * @param disable - Optional parameter to disable the click event handling. Defaults to false.
     */
    export function useOnClickOutside(
      ref: RefObject<HTMLElement>,
      callback: () => void,
      disable = false
    ) {
      useEffect(() => {
        function handleClickOutside(event: MouseEvent): boolean {
          if (disable) return false;
          if (ref.current && !ref.current.contains(event.target as Node)) {
            callback();
            return true;
          }
    
          return false;
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
          document.removeEventListener('mousedown', handleClickOutside);
        };
      }, [ref, callback, disable]);
    }
    
    

    If for some reason you don’t want to use this hook, you can take the useEffect part and put it directly in your component

    Login or Signup to reply.
  2. To close the navbar when clicking outside of it in a React component, you can use a combination of the useState and useEffect hooks along with event listeners. Here’s how you can implement this:

    import './SideNavBar.scss';
    import { useState, useEffect, useRef } from 'react';
    import { Cancel01Icon, Menu01Icon } from '../assets/icons';
    import { Link } from 'react-router-dom';
    
    const SideNavBar = () => {
      const [isOpen, setIsOpen] = useState(false);
      const navRef = useRef(null);
    
      const toggleMenu = () => setIsOpen(!isOpen);
    
      // Close the navbar if clicked outside
      const handleClickOutside = (event) => {
        if (navRef.current && !navRef.current.contains(event.target)) {
          setIsOpen(false);
        }
      };
    
      useEffect(() => {
        if (isOpen) {
          document.addEventListener('click', handleClickOutside);
        } else {
          document.removeEventListener('click', handleClickOutside);
        }
    
        // Cleanup event listener on component unmount
        return () => {
          document.removeEventListener('click', handleClickOutside);
        };
      }, [isOpen]);
    
      return (
        <>
          <button className="menu-button" onClick={toggleMenu}>
            {isOpen ? <Cancel01Icon className="sideicon" /> : <Menu01Icon className="sideicon" />}
          </button>
    
          <nav className={`side-navbar ${isOpen ? 'open' : ''}`} ref={navRef}>
            <ul className="side-navbar-ul">
              <li className="side-navbar-li"><Link to="/">Home</Link></li>
              <div className="line"></div>
              <li className="side-navbar-li"><Link to="/loja">Loja</Link></li>
              <div className="line"></div>
              <li className="side-navbar-li"><Link to="/galeria">Galeria</Link></li>
              <div className="line"></div>
              <li className="side-navbar-li"><Link to="/contato">Contato</Link></li>
              <div className="line"></div>
              <li className="side-navbar-li"><a href="#restrito">Restrito</a></li>
              <div className="line"></div>
            </ul>
          </nav>
        </>
      );
    };
    
    export default SideNavBar;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search