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

240
Visualizações
Why is document.getElementsByClassName not working in react?

So I have this piece of Code

const desc_object = document.getElementsByClassName("singlePostDesc");
console.log(desc_object[0]);

And this is the JSX

{updateMode ? (
                        <>
                            <textarea
                                className="singlePostDescInput"
                                autoFocus={true}
                                id="desc"
                                onChange={(e) => setDesc(e.target.value)}
                                onKeyPress={(e) => key_callback(e.key)}
                            >
                                {desc}
                            </textarea>
                            <button
                                className="singlePostButton"
                                onClick={update_post_to_backend}
                            >
                                Update Post
                            </button>
                        </>
                    ) : (
                        <div className="singlePostDesc" id="descThing">
                            <ReactMarkdown children={sanitizeHtml(desc)} />
                        </div>
                    )}

But I get the result as undefined. Why? Is it because it is wrapped in a ternary operator? I am using React JS.

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

0

In order to access DOM methods in react, you have to call this piece of code inside useEffect hook.

useEffect(() => {
  const desc_object = document.getElementsByClassName("singlePostDesc");
  if (desc_object) {
   // now you can access it here
  }

})

though the first time useEffect hooks runs getElementsByClassName will return undefined because the DOM is not mounted yet.

if you want to run this DOM query only after the component did mount, you can create a custom hook:

const useDidMountEffect = (func, deps) => {
 const didMount = useRef(false)

 useEffect(() => {
   if (didMount.current) func()
   else didMount.current = true
  }, deps)
}

and then you can use it like that:

useDidMountEffect (() => {
 const desc_object = document.getElementsByClassName("singlePostDesc");


})

UPDATE:

as comments mentioned, ideally you should not use vanilla js, you should use React Refs

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