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

223
Visualizações
Hide div when clicked outside the child div in ReactJs

I want to hide child div when clicked outside the child div. Toggle button should also work in this case.

import React, { useState } from "react";

export default function Toggle() {
  const [view, setView] = useState(false);
  return (
    <div style={{ height: "100vh", backgroundColor: "lightblue" }}>
     
      <button onClick={() => setView(!view)}> show/hide </button>
    
      <div 
        style={{
          display: `${view ? "block" : "none"}`,
          height: "20vh",
          width: "10vw",
          backgroundColor: "lightcoral",
        }}
      >
        Child Div
      </div>
      </div>
  );
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way of doing this is by getting the mouse cursor coordinates on click (using the event) and then adding a conditional statement to setView to false only if the cursor is outside the child div and the view is true.

export default function Toggle() {

const [view, setView] = useState(false);

  function hide(e) {
    if (e.pageX > 80 || e.pageY > 125) {
      if (view) setView(false);
    }
  }

  return (
    <div
      onClick={() => hide(event)}
      style={{ height: "100vh", backgroundColor: "lightblue" }}
    >
      <button onClick={() => setView(!view)}> show/hide </button>

      <div
        style={{
          display: `${view ? "block" : "none"}`,
          height: "20vh",
          width: "10vw",
          backgroundColor: "lightcoral"
        }}
      >
        Child Div
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza 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