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

340
Views
useRef TypeScript: no asignable para escribir LegacyRef<HTMLDivElement>

Estoy tratando de usar useRef con TypeScript pero tengo algunos problemas.

Con mi RefObject (supongo) necesito acceder al current . (es decir node.current )

He probado lo siguiente

  • const node: RefObject<HTMLElement> = useRef(null);
  • const node = useRef<HTMLElement | null>(null);

pero cuando voy a configurar la ref , siempre me dicen que X is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.

return <div ref={ node }>{ children }</div>

Editar: esto no debe restringirse a ningún tipo de elemento, por lo que no solo HTMLDivElement | HTMLFormElement | HTMLInputElement

Editar: Esto debería funcionar como un ejemplo

 import React, { useRef, RefObject } from 'react'; function Test() { // const node = useRef(null); // const node: RefObject<HTMLElement> = useRef(null); const node = useRef<HTMLElement | null>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={ node }></div> }
over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

Solo importa Reaccionar:

 import React, { useRef } from 'react'; function Test() { const node = useRef<HTMLDivElement>(null); if ( node && node.current && node.current.contains() ){ console.log("current accessed")} return <div ref={node}></div> }

Hice una actualización. Utilice HTMLDivElement como parámetro genérico en lugar de HTMLElement | null Además, contains espera un argumento.

ACTUALIZAR useRef espera un argumento genérico del tipo de elemento DOM. No es necesario utilizar | null porque RefObject ya sabe que la current podría ser nula.

Ver siguiente tipo:

 interface RefObject<T> { readonly current: T | null }

TS y React son lo suficientemente inteligentes como para darse cuenta de que su referencia podría ser nula

over 4 years ago · Santiago Trujillo Report

0

La clave es usar HTMLElement e indefinido para la inicialización

 const node = useRef<HTMLElement>();
over 4 years ago · Santiago Trujillo Report

0

Vine aquí en busca de ayuda con un iframe ref. Quizás esta solución ayude a alguien más que esté buscando lo mismo. HTMLDivElement con HTMLIFrameElement así:

 const node = useRef<HTMLIFrameElement>(null);
over 4 years ago · Santiago Trujillo Report

0

Ninguno de los anteriores funcionó para mí, pero resulta que la solución fue bastante simple...

Todo lo que estaba haciendo mal era no incluir explícitamente "null" como parámetro en la inicialización de useRef (espera nulo, no indefinido). Además, NO PUEDE usar "HTMLElement" como su tipo de referencia, debe ser más específico, así que para mí fue "HTMLDivElement", por ejemplo).

Entonces, el código de trabajo para mí fue algo como esto:

 const ref = useRef<HTMLDivElement>(null); return <div ref={ref}> Some Content... </div>
over 4 years ago · Santiago Trujillo 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!