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

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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