I have a responsive nav bar in a react app, when the screen size shrinks, the nav buttons disappear and a menu icon appears. I have some state set up where if you click the menu icon, the nav buttons appear in a drop down below it. I would like it so if you click anywhere on the screen or resize the window, the state changes and closes the drop down. But as of right now, the only way I can get the dropdown to close is to click the icon. Can anyone help me change the state on any click event?
Here is my jsx
import React from 'react';
import menu from '../images/menu.png';
export default function Nav() {
const [isExpanded, setIsExpanded] = React.useState(false);
function toggleNav() {
setIsExpanded(!isExpanded);
}
return (
<nav className="navBar">
<a href="#main" className="navMainLogo">Nick J's Code Blog!</a>
<img src={menu} alt="menu icon" className="menuIcon" onClick={toggleNav}></img>
<div className="navButtons" id={isExpanded ? "expanded" : ""}>
<a className="firstButton" href="#feed">Blog Posts</a>
<a href="google.com">About</a>
<a href="google.com">My Portfolio</a>
</div>
</nav>
)
}
Here is my css
/*nav Bar */
.navBar {
height: 60px;
width: 100%;
position: fixed;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
font-family: "Montserrat", sans-serif;
color: white;
background-color: var(--color2);
}
.navMainLogo {
margin-left: 30px;
}
.navButtons {
width: 50%;
}
.navButtons {
width: 50%;
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.navButtons ul li {
list-style: none;
}
.navBar a {
color: white;
text-decoration: none;
}
nav a:hover {
color: var(--color4);
}
.menuIcon {
margin-right: 30px;
margin-left: auto;
display: none;
width: 20px;
}
.menuIcon:hover {
cursor: pointer;
}
@media screen and (max-width: 560px) {
.navBar .menuIcon {
display: block;
}
.navButtons {
display: none;
}
#expanded {
margin-left: 50%;
justify-content: center;
align-items: center;
background-color: var(--color2);
position: absolute;
display: flex;
flex-direction: column;
margin-top: 145px;
}
#expanded a {
margin: 5px;
}
}