Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
¿Por qué document.getElementsByClassName no funciona en reaccionar?

Así que tengo este pedazo de Código

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

Y este es el 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> )}

Pero obtengo el resultado como undefined . ¿Por qué? ¿Es porque está envuelto en un operador ternario? Estoy usando React JS.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Para acceder a los métodos DOM en reaccionar, debe llamar a este fragmento de código dentro del gancho useEffect .

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

aunque la primera vez useEffect hooks ejecute getElementsByClassName devolverá undefined porque el DOM aún no está montado.

si desea ejecutar esta consulta DOM solo después de que el componente se montó, puede crear un enlace personalizado:

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

y luego puedes usarlo así:

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

ACTUALIZAR:

como se menciona en los comentarios, idealmente no deberías usar vanilla js, deberías usar React Refs

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!