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

241
Vistas
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 Respuestas
Responde la pregunta

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 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