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

82
Visualizações
Update className using react hook

I have a span which has a className . The span has two state, one is like

<span  key={uuid()} ref = {colorRef} className = 'singleWord'>{word}</span>

and the other is like

<span  key={uuid()} ref = {colorRef} className = 'singleWord redword'>{word}</span>

Now what I want is to check the className value like className.classList.contain("oneClass') which we do in vanilla js but I need in react hook(may be with ref hook) and also add className and remove className . also is it possible to check the length of className .for example 'singleword redword' should give length 2. So overall I need -

  1. add or remove classes
  2. check length
  3. check if class contains or not I need to check them in react hook could anybody suggest how to do ?? Thanks in advance
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can store in state an array of classes and use that to get all the information you need plus it gives an easy way to toggle any class in a set of classes.

basically this handleClasses function takes a class argument and then checks whether that class is already in your state. If it is, it removes it, if it's not, it add it to the state. Then in your span you join all the classes in the array in state to make a single string of classes.

Also you get the number of classes applied to your element very easily by doing classes.length

import React, { useState } from 'react';

const Component = () => {
  const [classes, setClasses] = useState(['singleWord']);

  const numberOfClasses = classes.length;

  const handleClasses = (c) => {
    setClasses(classes.includes(c)
      ? classes.filter((cls) => cls !== c)
      : [...classes, c]
    )
  }

  return (
    <span
      onClick={() => handleClasses(passClassToToggleHere)}
      className={classes.join(' ')}
    >
      text
    </span>
  )
};


about 4 years ago · Juan Pablo Isaza Relatório

0

If you are using colorRef = useRef() hook, then you can obtain the target node by calling colorRef.current and proceed with vanilla js methods like colorRef.current.classList.contain("oneClass') and so on.

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