Reputation: 88
I want to log the user out when I click on the "logout" element located inside the dropdown menu.
but the onClick event is not firing when I click on that.
this is the code
<nav className="navbar navbar-expand-sm navbar-dark bg-dark mb-4">
...
<ul className="navbar-nav ml-auto">
<li className="nav-userdata dropdown" data-toggle="dropdown" role="button"
aria-haspopup="true" aria-expanded="false" >
<img src={user.avatar} className={"avatar"} alt={"user avatar"}
/>
<div className="dropdown-toggle" >{user.name}</div>
<ul className="dropdown-menu bg-dark">
<li><a href={"#"} onClick={() => console.log("logout")}>Logout</a></li>
<li><a href="#">Dashboard</a></li>
</ul>
<span className="caret"></span>
</li>
</ul>
...
</nav>
there are no errors in console ,onClick work as intended when i add it outside the dropdown menu.
is there a way to make this work while using bootstrap dropdown menu?
Upvotes: 0
Views: 2831
Reputation: 88
I managed to fix this issue by manually toggling the 'show' class in dropdown menu
const [isDropdownOpen,setDropdown] = useState(false);
const logout = () => {
dispatch(logoutUser());
};
<nav className="navbar navbar-expand-sm navbar-dark bg-dark mb-4">
...
<ul className="navbar-nav ml-auto" onClick={() => setDropdown(!isDropdownOpen)}>
<li className="nav-userdata dropdown" >
<img src={user.avatar} className={"avatar"} alt={"user avatar"}
title={"You must have a gravatar connected to display the avatar"}/>
<div className={"dropdown-toggle"}>{user.name}</div>
<ul id={'dropdown-userdata'} className={classnames('dropdown-menu bg-dark dropdown-userdata', {'show': isDropdownOpen})}>
<li><a href={'#'} className='nav-link' onClick={logout}>Logout</a></li>
<li><Link to={'/dashboard'} className={'nav-link'}>Dashboard</Link></li>
</ul>
<span className="caret"></span>
</li>
</ul>
...
</nav>
Upvotes: 1
Reputation: 664
You need e.preventDefault() in the click handler.
It's firing but the default behavior of an anchor is to refresh the page, so
it's just rerendering immediately.
<li><a onClick={(e) => this.logout(e)}>Logout</a></li>
logout =(e) =>{
e.preventDefault()
console.log('logout')
}
try something like this,may it work
Upvotes: 0
Reputation: 28
While function call closing the anchor tag without and after that only the onclick functionality will work. I think every thing is fine with your work but the arrow symbol is overriding the anchor tag closing. So just check it will work fine
Upvotes: 0