Now that we've seen how we can set up a manual event listener, we need to figure out how to make use
of this inside of our code, the back inside of our editor.
I'm going to find my dropdown component.
You might recall that the last widget that we worked on, we covered the use effect hook so we can set
up a use effect.
Hoak inside of dropdown and inside there, whenever our component is first rendered onto the screen,
we could set up an event listener to just, well, listen to that body element.
So let's try this out at the very top next to you, states all add in a U.S. effect.
Then after hour, you state right there, I'm going to call this effect.
And I want to make sure that this area function right here only runs one time when we first render our
component onto the screen.
I only want to run it one time because I only need to set up the event listener one time.
So to make sure this thing only runs once, we will put in a argument or the second element right there
of an empty array.
And then inside there, we can right in our event listener, so we will do a documentary body add event
listener.
We will watch very klick.
And then right now, we'll just do the same thing, a council log of.
I'll then save this look back over.
And now whenever we click anything, we'll see that council log appear.
There's one I can open the dropdown, select an item.
In every case, I get a council log.
OK, well, that definitely looks good.
So now we should be able to replace that slug with some logic to just close the dropdown.
Now, I just want you to know that our initial solution here is not going to work out.
We're going to have to apply a little bit of knowledge around effect.
But let's just try just try something right.
Let's just get started somewhere.
So as we've discussed, we want to make sure that whenever a user clicks anywhere on our document,
we try to close the dropdown.
And that would imply that we want to set open to false input.
Set openside appear to false.
OK, so let's look back over.
I'll then go ahead and open the drop down.
OK, that looks good, and then I will click outside of it.
Hey, it closed, right?
Well, not quite.
We're not there yet.
Take a look at this.
If I click on that thing and then click on an option, notice how the dropdown now stays open.
Ideally, whenever we click on an option, we want the whole thing to close, as it did just a little
bit ago before we just added in this additional event listener.
So it's clear that this thing kind of works as a solution, but also kind of doesn't work.
So why is this occurring?
Well, yet again, quick pause, then take a look at a couple of diagrams and understand why this little
quick fix right here didn't quite work the way we expected.