2

What is the most efficient way to close menu on click in React functional component? I'm trying to get <Menu /> close on clicking either <Link />or outside menu. Currently it stays open when I navigate to other component.

I use: https://github.com/negomi/react-burger-menu

MobileMenu.js

import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { elastic as Menu } from 'react-burger-menu';
import './MobileMenu.scss';

const MobileMenu = () => {
    
const [menuOpenState, setMenuOpenState] = useState(false)

const MyContext = React.createContext();

// const showSettings = event =>{
//     event.preventDefault();
// }
  return (
    <div className="mobileMenu" id="outer-container"> 
        <Menu right pageWrapId={ "page-wrap" } outerContainerId={ "outer-container"} isOpen={ false }>
            <main id="page-wrap">
                <MyContext.Provider value={{
                    isMenuOpen: menuOpenState,
                    toggleMenu: () => setMenuOpenState(!menuOpenState),
                    stateChangeHandler: (newState) => setMenuOpenState(newState.isOpen)
                }}>
                </MyContext.Provider>
                <Link id="home "to={'/'} className="menu-item">home</Link>
                <Link id="projects" to={'/projects'} className="menu-item">projects</Link>
                <Link id="experiment" to={'/experiment'} className="menu-item">experiment</Link>
                {/* <a onClick={ showSettings } className="menu-item--small" href="/">Settings</a> */}
            </main>
        </Menu>
    </div>
  )
}
export default MobileMenu
inhyechoi
  • 107
  • 1
  • 2
  • 11
  • 1
    Do not know about efficiency, but this hook can do the trick https://usehooks.com/useOnClickOutside/ – David Galoyan Oct 19 '20 at 18:00
  • Go with the implementation @DavidGaloyan shared. That is how it would be implemented in a component, and wrapping it all in a reusable hook is nice as well. – Drew Reese Oct 19 '20 at 19:01

1 Answers1

0

one way to do it is add a div element with absolute value and stretch the entire screen display on let's say z-index: 100; and your menu on z-index: 101; and open the element only with the menu and set the onClick={() =>setMenuOpenState(false)} this way it's a little more efficient

Adarsh
  • 428
  • 5
  • 16