Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
How do I add a class to a react element when it is clicked

I have this react component and I am trying to create a hamburger menu but, I don't know how to add a class when a button is clicked. I am new to React so please go easy on me. When I run the below code it doesn't work and throws an error in the Chrome dev tools.

function Nav() {
const hamburger = document.getElementById('hamburger');
const navUL = document.getElementById('navul');
hamburger.addEventListener('click', () =>{
  navUL.classList.toggle('show');
});
  return (
<header>

  <h2>
    <a href="/">
      Travis Helms
    </a>
  </h2>
  <nav>
    <ul className="flex-row" id='navul'>
      <li className="mx-2">
        <a href="#about">
          About me
        </a>
      </li>
      <li>
        <span>Portfolio</span>
      </li>
      <li>
        <span>Contact</span>
      </li>
      <li>
        <span>Resume</span>
      </li>
    </ul>
  </nav>
  <button className="hamburger" id="hamburger">
    <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
    </button>
    </header>
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Ok. So I went to a tutor and worked with them to come up with this solution to toggle my hamburger menu. Just thought I would add this answer for the benefit of other beginning React programmers.

import React,{ useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBars } from '@fortawesome/free-solid-svg-icons';

function Nav(props) {
const [navClass, setnavClass]= useState("flex-row");
const [toggledNav, settoggledNav]= useState(true);

const addClass=() => {
  if (toggledNav){
    setnavClass("flex-row show");
    settoggledNav(false);
  }else {
    setnavClass("flex-row");
    settoggledNav(true);
  }

}

  return (
<header>

  <h2>
    <a href="/">
      Travis Helms
    </a>
  </h2>
  <nav>
    <ul className={navClass} id='navul'>
      <li className="mx-2">
        <a href="#about">
          About me
        </a>
      </li>
      <li>
        <span>Portfolio</span>
      </li>
      <li>
        <span onClick={() => props.setmenuSelect(1)}>Contact</span>
      </li>
      <li>
        <span>Resume</span>
      </li>
    </ul>
  </nav>
  <button onClick={addClass} className="hamburger" id="hamburger">
    <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
    </button>
    </header>
  );
}

export default Nav;
about 4 years ago · Juan Pablo Isaza Denunciar

0

First of all, welcome to React! It's an amazing framework!

It would have been more helpful if you provided the error you are getting but from the code you shared I can see there are a few things you need to do differently.

Generally, you can use event listeners in React for certain things, and there is a certain way to add them properly, but for the most part they are not used very frequently. Instead, for example, to assign a click event to an element in React, all you need to do is pass it the onClick attribute with the function you want it to execute when it is clicked, for example <button onClick={doSomething}>click me</button>.

An easy way to control the state of your component is by using the useState hook and toggle the class of an element using state. In your case, it could look like this:

import React, { useState } from 'react';

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

    return (
        <header>
            <h2>
                <a href="/">Travis Helms</a>
            </h2>
            <nav>
                <ul className={"flex-row " + (isOpen ? "show" : "")}>
                    <li className="mx-2">
                        <a href="#about">About me</a>
                    </li>
                    <li>
                        <span>Portfolio</span>
                    </li>
                    <li>
                        <span>Contact</span>
                    </li>
                    <li>
                        <span>Resume</span>
                    </li>
                </ul>
            </nav>
            <button
                className="hamburger"
                onClick={() => setIsOpen(!isOpen)}
            >
                <FontAwesomeIcon icon={faBars}></FontAwesomeIcon>
            </button>
        </header>
    );
};

It looks like you are in a very early stage of learning React and for you to be successful coding with React you need to cover a few basics like state management, props, children and a few more things. I would recommend going on YouTube and find a good introduction video to React and code along to it! There are a lot of great resources in there for people who are just starting with React, just make sure it's something fairly recent (I'd say 2020 onwards).

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda