DEV Community

Cover image for How to create a popup menu in React that closes on clicking outside (module)
Kunal Bagaria
Kunal Bagaria

Posted on • Edited on

How to create a popup menu in React that closes on clicking outside (module)

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>
        )}
    )
};
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
enochndika profile image
Enoch Ndika

This can be easily done with useRef hook. why use an npm package for basic stuff?

Collapse
 
kunal profile image
Kunal Bagaria

Yeah, I could have shown that but thought that this would be easier for people, appreciate the feedback though :)

Collapse
 
charlesinwald profile image
charlesinwald

I find the title misleading in that case. When you rely heavily on a library like this, include it in the title.

Thread Thread
 
kunal profile image
Kunal Bagaria

Sure, I'll update the title :)

Collapse
 
anshrk profile image
Anshrk

Really cool, Hype for the "Center the div" tutorial

Collapse
 
kunal profile image
Kunal Bagaria

Haha, easy one to make, no worries, gonna make it soon

Collapse
 
saulodias profile image
Saulo Dias

I didn't search for this. I only followed because of Starship.

Collapse
 
yeasin2002 profile image
Md Kawsar Islam Yeasin

why you need to use any kind of npm packages for this kind of simple stuff.