Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to hide box on body click except of button in using ReactJS Hooks?

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;

about 4 years ago · Juan Pablo Isaza Report

0

There's many tricks to solve this. But one of them I prefer, do it like modals. So:

  1. Add background div beside of the box that shows back of the box
  2. Set onClick on this new div to hide the box
function 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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!