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?
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?
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)} />
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.