1

Have an issue for you.

I'm making a React App and want to implement one feature

Imagine we have a 'X' icon. When we click on it div emerges BUT after we click in any place outside of the div it becomes hidden again.

How to create such function?

AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
  • create state and check if it outside of the area then close it, for checking outside area https://stackoverflow.com/questions/36695438/detect-click-outside-div-using-javascript – Nisharg Shah Dec 27 '20 at 19:24

2 Answers2

1

use window.onclick event to hide it, note that you have to check the event.target is not your div or one of it child.

for react create state on your root component, change it on onclick and walk down it target child. like this:

class MyApp extends React.Component{
   constructor(props){
      super(props)
     this.state = {
       DivVisible:false,
     }
   }

 CloseDiv(){
    this.setState({DivVisible : false})
}

OpenDiv(){
    this.setState({DivVisible : true})
}

setDivVisible(v){
    if(v)
        this.OpenDiv()
    else 
        this.CloseDiv()
}

render(){
    return <div onClick={() => {this.CloseDiv()}}>

        <MyComponent DivVisible={this.state.DivVisible}  
                setDivVisible={(v) => { setTimeout(()=>{this.setDivVisible(v)}, 100) } } 
                index={this.state.pageIndex}
                goto={(i)=>this.goto(i)} />

    </div>
    
 }
}//end class

let the state DivVisible and the function setDivVisible walk down to child of MyComponent until you reach to target child then set the css style like this:

  <MyChild  style={{display:props.DivVisible? 'block':'none'}} onclick={)(()=>props.setDivVisiable(true)} />
Hani
  • 149
  • 1
  • 3
1

Here is a very crude version: https://codesandbox.io/s/elated-wilbur-wn8e6?file=/src/App.js:0-844

import React from "react";
import "./styles.css";

export default function App() {
  const [show_div, setShowDiv] = React.useState(false);

  React.useEffect(() => {
    window.addEventListener("click", function (event) {
      if (event.target.id !== "mydiv" && event.target.id !== "clicker") {
        setShowDiv(false);
      }
    });
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <a href="#" id="clicker" onClick={() => setShowDiv(!show_div)}>
        X
      </a>

      {show_div ? (
        <div id="mydiv" className="dima">
          This Div is showing
        </div>
      ) : null}
    </div>
  );
}

Obviously this is not a production example, but it will get you started.

codemonkey
  • 7,325
  • 5
  • 22
  • 36