1

I have created my Responsive Hamburger menu in React. It works fine on Desktop however the hamburger doesn't drop when clicked, it shows this error when clicked ::

TypeError: Cannot read properties of null (reading 'classList')
hamClick
src/hamburger.js:24
  

    21 | 
      22 | const hamClick = (e) => {
      23 |     e.preventDefault();
    > 24 |     if(header.classList.contains('open')){//close hamburger
         | ^  25 |         body.classList.remove('noscroll');
      26 |         header.classList.remove('open');
      27 |         fadeElems.forEach(function(element){

THIS is my code for the Hamburger functionality;;

import React from 'react';

import "./scss/animations.scss";
import './scss/header.scss';
import './scss/mixins.scss';




const Hamburger = () => {

    const btnHamburger = document.querySelector('#btnnHamburger');

    const body = document.querySelector('body');

    const header = document.querySelector('.header');

    const overlay = document.querySelector('.overlay');

    const fadeElems = document.querySelectorAll('.has-fade');
    
    const hamClick = (e) => {
        e.preventDefault();
        if(header.classList.contains('open')){//close hamburger
            body.classList.remove('noscroll');
            header.classList.remove('open');
            fadeElems.forEach(function(element){
                element.classList.remove('fade-in');
                element.classList.add('fade-out');
            });    
        }
        else{//open hamburger
            body.classList.add('noscroll');
            header.classList.add('open');
            fadeElems.forEach(function(element){
                element.classList.add('fade-in');
                element.classList.remove('fade-out');
            });   
        }
    }


    return(
        <a id="btnnHamburger" className="header__toggle hide-for-desktop" href="#" onClick={hamClick}>
            <span></span>
            <span></span>
            <span></span>
        </a>
    )
}

export default Hamburger;

Please can you help me understand what I need to do correctly

Palani
  • 21
  • 5
  • You're not supposed to use DOM manipulation when using React. Use a state variable instead: https://reactjs.org/docs/hooks-state.html –  Oct 11 '21 at 12:58
  • Oh man, it looks like abusing React... – Robo Robok Oct 11 '21 at 12:58
  • Why do want to use react when you are using just vanilla js for DOM manipulation? You are not supposed to do direct dom manipulation because react takes care of it using `reconcilliation` and `Virtual DOM` please refer to [docs](https://reactjs.org) – Sachin Ananthakumar Oct 11 '21 at 13:06
  • I previously created the landing page with just HTML, CSS and JS. I am now creating an App using Create-React-App so I am trying to convert the functionality to ReactJs, that's where am facing the challenge – Palani Oct 11 '21 at 14:15

0 Answers0