T have a button with a box & box will hide/show (toggle) on button click. This is working fine now I want to when we click on body except of button then box should be hide.
My Code:-
function App() {
const [show, setShow] = useState(false);
return (
<div>
<button className="btn" onClick={() => setShow(!show)}></button>
{show ? <div className="box"></div>
: null}
</div>
);
}
export default App;
ThankYou for your efforts!
If I got your point rightly. You can solve it like this. It will close the box/modal when one clicks outside of the modal or body
function App() {
const [show, setShow] = useState(false);
return (
<div>
<button className="btn" onClick={() => setShow(!show)}></button>
{show ?
<div onClick={() => setShow(false)}
style={{width: '100vw',
height: '100vh',
position: 'absolute',
top: 0,
left: 0
}}>
<div className="box" onClick={(e) => e.stopPropagation()}></div>
</div>
);
}
export default App;
There's many tricks to solve this. But one of them I prefer, do it like modals. So:
box that shows back of the boxfunction App() {
const [show, setShow] = useState(false);
return (
<div>
<button className="btn" onClick={() => setShow(!show)}></button>
{show && (
<>
<div style={{bottom:0 , top:0, right:0, left:0,position:"absolute"}} onClick={()=> setShow(false)}></div>
<div className="box"></div>
</>)
}
</div>
);
export default App;