DEV Community

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

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

Kunal Bagaria
Full Stack Developer
Updated on ・1 min read

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.

Discussion (8)

Collapse
enochndika profile image
enoch ndika

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

Collapse
kb24x7 profile image
Kunal Bagaria Author

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
kb24x7 profile image
Kunal Bagaria Author

Sure, I'll update the title :)

Collapse
anshrk profile image
Anshrk

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

Collapse
kb24x7 profile image
Kunal Bagaria Author

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
kb24x7 profile image
Kunal Bagaria Author

A big fan of Starship as well XD
Join my Discord if you wanna interact with like minded people:
discord.gg/eBaFj2ytTU