From the course: Master Next.js by Building Scalable Apps with Routing, Databases, and Performance

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Close profile drop-down menu on outside click

Close profile drop-down menu on outside click

In the previous lecture, we built the user profile drop-down. By now, you are familiar with the concept of an ideal user-friendly drop-down menu, which automatically closes when the user clicks outside of it. Now, let's go to the browser and open the profile drop-down. When I click outside the drop-down menu, notice that it remains open. Ideally, it should close automatically when we click anywhere else. So let's implement the functionality to close the drop down when clicked outside the box. I will navigate to the header component and create a drop down reference by importing use ref from the react library. Now I will create a reference for drop down by using const drop down ref is equal to use ref and passing null inside. Also assigning this reference to the parent div of drop down by saying ref is equal to drop down ref. Let's create a function. So I'll say const handle click outside. We'll have the event object. Inside this function, I will check if the reference contains the…

Contents