How to use ClickAwayListener Component in ReactJS ?
Last Updated :
10 Nov, 2023
Detect if a click event happened outside an element. Whenever the user clicks somewhere in the document, this listener works. Material UI for React has this component available for us, and it is very easy to integrate.
Prerequisites:
Approach:
To use ClickAwayListener Component in ReactJS we will wrap the clickAwayListener component around the React Code where we want to detect the click. We will create a button inside and detect the click outside this button component.
Steps to Create React Application And Installing Modules:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm i @material-ui/core
Project Structure:
Project Structure
The updated dependencies in package.json file will look like.
"dependencies": {
"@material-ui/core": "^4.12.4",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4
}
Example: This example implements clickAwayListener to capture the click outside the button.
Javascript
import React from "react" ;
import { lightBlue } from "@material-ui/core/colors" ;
import ClickAwayListener from "@material-ui/core/ClickAwayListener" ;
export default function App() {
const [open, setOpen] = React.useState( false );
const handleClickAwayEvent = () => {
setOpen( false );
};
const handleClickEvent = () => {
setOpen((prev) => !prev);
};
return (
<div style={{ display: "block" , padding: 30 }}>
<h4>
How to use ClickAwayListner Component in
ReactJS?
</h4>
<ClickAwayListener
onClickAway={handleClickAwayEvent}
>
<div
style={{
position: "relative" ,
}}
>
<button
type= "button"
onClick={handleClickEvent}
>
ClickAwayListener Demo
</button>
{open ? (
<div
style={{
width: 150,
position: "absolute" ,
right: 0,
fontSize: 9,
border: "1px solid" ,
left: 0,
backgroundColor: lightBlue,
zIndex: 1,
padding: 3,
top: 28,
}}
>
It will be visible until you
click outside this box
</div>
) : null }
</div>
</ClickAwayListener>
</div>
);
}
|
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Share your thoughts in the comments
Please Login to comment...