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

152
Visualizações
How to remove added classes from an element in reactjs

I am making a drag n drop sort of game where you match the logos with their corresponding name.

If user matches the logo with the name correctly than the field which you could drop the logo gets additional classes.

Like this:

if (isCorrectMatching) {
  event.target.classList.add("dropped");
  draggableElement.classList.add("dragged");
  event.target.classList.add("dragged");
  event.target.setAttribute("draggable", "false");
  draggableElement.setAttribute("draggable", "false");
  event.target.innerHTML = `<i class="fab fa-${draggableElementBrand}" style="color: ${draggableElement.style.color};"></i>`;
}
    

If every match is found user can go to next level , my problem is that these additional classes are staying there , how do I remove them ?

I am mapping them out like this:

<div className="containerItems">
  {draggableItems.map((x, i) => {
    return (
      <div className="draggable-items">
        <i
          onDragStart={(e) => dragStart(e)}
          className={`draggable fab fa-${x}`}
          id={x}
          draggable="true"
          ref={draggableOnes.current[i]}
        ></i>
      </div>
    );
  })}
</div>;

{
  matchingPairs.map((x, i) => {
    return (
      <section className="matching-pairs">
        <div className="matching-pair">
          <span className="label">{x}</span>
          <span
            className="droppable"
            // ref={droppableOnes.current[i]}
            onDragEnter={(e) => dragEnter(e)}
            onDragOver={(e) => dragOver(e)}
            onDragLeave={(e) => dragLeave(e)}
            onDrop={(e) => drop(e)}
            data-brand={x}
          ></span>
        </div>
      </section>
    );
  });
}

I can not seem to solve this one, like how do I remove all the classes that I've added when there was a correct matching.

I would like to remove basically everything that I've added in my if (isCorrectMatching) .

I've tried to use refs but it did not work. What is the way to go for this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In React, you don't directly manipulate DOM elements (well, almost never), including their the class lists. Instead, you keep your state information in the component and use that state information to render the elements that make up your component (including their classes). React will then compare the rendered elements you return with the DOM and make any necessary changes (such as updating the classList). So in your code, when you see that you have a correct matching, you wouldn't directly modify those DOM elements' classList lists, you'd update your state to remember the match, and use that state information in the next render to put the appropriate classes on the elements being rendered.

Here's a simpler example with a tickbox, but it's the same general concept:

const {useState} = React;

const Example = () => {
    const [isChecked, setIsChecked] = useState(false);
    return <div>
        <label>
            <input
                type="checkbox"
                checked={isChecked}
                onChange={() => setIsChecked(flag => !flag)}
            />
            Ticked
        </label>
        <div className={isChecked ? "yes" : "no"}>
            Example
        </div>
    </div>;
};

ReactDOM.render(<Example />, document.getElementById("root"));
.yes {
    color: green;
}
.no {
    color: #d00;
}
label {
    user-select: none;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

Note how the state member isChecked determines what classes the div has, and is updated by ticking/unticking the checkbox.

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