1

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>
  );
}
Shekhar
  • 27
  • 6
  • You can check the updated, 2021 answer to this post: https://stackoverflow.com/questions/32553158/detect-click-outside-react-component – Jayce444 Jan 05 '22 at 06:51

1 Answers1

1

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>
  );
}
Gass
  • 7,536
  • 3
  • 37
  • 41