`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
You can use this hook that I wrote before:
If for some reason you don’t want to use this hook, you can take the
useEffect
part and put it directly in your componentTo close the navbar when clicking outside of it in a React component, you can use a combination of the
useState
anduseEffect
hooks along with event listeners. Here’s how you can implement this: