Skip to content

How to close the menu when clicking on the document (EventListener)

I have been trying to add an EventListener to the document to close my menu, but it seems that none of the event.stopPropagation(); actually listen to me :/ can anyone give me a hand here? Please

import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import "./header.css";
class Header extends Component {
    constructor(props) {
        this.state = {
            language : "en"
    openMenu = () => {
        let menuPaths = document.getElementById('menu');
        let hideAnimation = () => {
        let showAnimation = () => {
        if(menuPaths.classList.contains('show')) {
        } else {
    render() {
        //user logged in? render nav. Else, render login/signup
        const userAction = (
            <div className='header_action'>
                <button className='header_action_signup orange-md-btn'>SIGN UP</button>
                <button className='header_action_login orange-md-btn'>LOGIN</button>
        return (
            <div className='header'>
                <div className="header_menu">
                    <img onClick={event => {
                        return this.openMenu(event);
                    }} src={require("./pictures/hamburger_menu.svg")}/>
                <div className='header_paths' id="menu">
                    <NavLink to='/index/acceuil'>Home</NavLink>
                    <NavLink to='/index/how'>How does it work</NavLink>
                    <a href= {BLOG_URL + '/'+ this.state.language +'/'}>Blog</a>
                    <a href={BLOG_URL + '/media/'}>Media</a>
                    <NavLink to='/index/contact'>Contact Us</NavLink>
                    <a href={PUBLIC_MARKETPLACE}>Marketplace</a>
                    <a href="#">Fr</a>
                <NavLink to='/index/acceuil' className='header_logo' >
                    <img src={require("./pictures/logo_march2.png")}/>
export default Header;

this is what I tried adding in the openMenu function

document.addEventListener("click", function(event) {
            document.removeEventListener("click", this.hideAnimation());

I also tried attaching the removeEventHandler on click in the componentDidMount, that didn’t work and I’ve tried numerous combinations of event.preventDefault();. I got it before using jQuery, however now that I have to use react, I don’t want to mix is with jQuery. Any ideas?


  1. First of all, you need to do toggling your menu with state but not changing the DOM directly.
  2. From what I understand your question, you want to close the menu upon clicking outside of the menu. If it is so, you might wanna use react-onclickoutside and create handleClickOutside function and passed it to the HOC.