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

247
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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