So here you are, you want to make your popup in your website but you can't find a good tutorial on how to do that. Fear not, your friendly neighborhood react developer is here to save the day.
First things first, we are gonna use an external npm module to make things easier.
yarn add react-click-away-listener
or
npm i react-click-away-listener
Now, on to the syntax:
You can find additional docs here: Link
import { useState ) from 'react';
import ClickAwayListener from 'react-click-away-listener';
const App = () => {
const [popup, setPopup] = useState(false)
return (
{/* The option to open the popup */}
<button onClick={() => setPopup(true)}>Click Me</button>
{/* The popup itself */}
{popup && (
<ClickAwayListener onClickAway={() => setPopup(false)}>
<div className={'popup'}>
<li>Items of the Popup</li>
<li>Items of the Popup</li>
<li>Items of the Popup</li>
</div>
</ClickAwayListener>
)}
)
};
There you have it, that's basically how you can make a click away listening popup in react. I have excluded the styling portion for this article, but I'll be sure to write up on it soon.
Top comments (8)
This can be easily done with useRef hook. why use an npm package for basic stuff?
Yeah, I could have shown that but thought that this would be easier for people, appreciate the feedback though :)
I find the title misleading in that case. When you rely heavily on a library like this, include it in the title.
Sure, I'll update the title :)
Really cool, Hype for the "Center the div" tutorial
Haha, easy one to make, no worries, gonna make it soon
I didn't search for this. I only followed because of Starship.
why you need to use any kind of npm packages for this kind of simple stuff.