Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda