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

160
Vistas
why we use ref.current instead of just put the condition

can anyone tell me why we use if (ref.current && !ref.current.contains(event.target)) instead of if (!ref.current.contains(event.target))

function useOutsideAlerter(ref) {
  useEffect(() => {
 
    // Function for click event
    function handleOutsideClick(event) {
      if (ref.current && !ref.current.contains(event.target)) {
        alert("you just clicked outside of box!");
      }
    }
 
    // Adding click event listener
    document.addEventListener("click", handleOutsideClick);
    return () => document.removeEventListener("click", handleOutsideClick);
  }, [ref]);
}
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

So main issue is that ref may not be set on first render. It was guarantied to be set in componentDidMount, when we used classes for example, but in functional components it's a little bit more tricky, since we don't have such thing as lifecycles and we have an effects, so it's useful to check, if that ref value is set.

about 4 years ago · Santiago Trujillo Denunciar

0

According to the docs

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

ref itself might have a value, but to access the element you need to use ref.current which can be undefined.

To make your syntax shorter you can use Optional chaining

if (!ref.current?.contains(event.target) {
  // ...
}
about 4 years ago · Santiago Trujillo Denunciar

0

The property .current can be null, so e just have to safe guard that the property is Not null before trying to read the .current property. Remember .current is set after the function returns.

about 4 years ago · Santiago Trujillo 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