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

224
Vistas
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 Respuestas
Responde la pregunta

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