Quiero ocultar el div secundario cuando se hace clic fuera del div secundario. El botón de alternar también debería funcionar en este caso.
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> ); }
Una forma de hacer esto es obtener las coordenadas del cursor del mouse al hacer clic (usando el evento) y luego agregar una declaración condicional para setView
en falso solo si el cursor está fuera del div secundario y la view
es verdadera.
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> ); }