i have created a simple react project and i was trying to implement drop down list in it.
i am trying to create a dropdown list for profile in react like this->
dropdown.js
import React, { useState } from "react";
import "./style.css";
function DropdownNavbar() {
const [toggle, setToggle] = useState(false);
const menuToggle = () => {
setToggle(!toggle);
};
return (
<>
<div className="new-box d-flex" onClick={menuToggle}>
<div className="profile p-2 flex-fill">
<img src="images/avatar-img.png" />
</div>
<div className="name-text p-2 flex-fill">Alex John</div>
</div>
{toggle && (
<div class="menu">
<ul>
<li>
<a href="#">My profile</a>
</li>
<li>
<a href="#">Inbox</a>
</li>
<li>
<a href="#">Logout</a>
</li>
</ul>
</div>
)}
</>
);
}
export default DropdownNavbar;
style.css
.new-box{
display: flex;
}
.name-text{
margin-top: 15px;
}
.profile {
position: relative;
width: 40px;
height: 40px;
border-radius: 50%;
overflow: hidden;
cursor: pointer;
margin: 5px 10px 5px 0px;
}
.profile img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.menu {
position: absolute;
top: 120px;
right: -10px;
padding: 10px 20px;
background: #fff;
width: 200px;
box-sizing: 0 5px 25px rgba(0, 0, 0, 0.1);
border-radius: 15px;
transition: 0.5s;
visibility: hidden;
opacity: 0;
}
.menu.active {
top: 80px;
visibility: visible;
opacity: 1;
}
.menu::before {
content: "";
position: absolute;
top: -5px;
right: 28px;
width: 20px;
height: 20px;
background: #fff;
transform: rotate(45deg);
}
.menu h3 {
width: 100%;
text-align: center;
font-size: 18px;
padding: 20px 0;
font-weight: 500;
color: #555;
line-height: 1.5em;
}
.menu h3 span {
font-size: 14px;
color: #cecece;
font-weight: 300;
}
.menu ul li {
list-style: none;
padding: 16px 0;
border-top: 1px solid rgba(0, 0, 0, 0.05);
display: flex;
align-items: center;
}
.menu ul li img {
max-width: 20px;
margin-right: 10px;
opacity: 0.5;
transition: 0.5s;
}
.menu ul li:hover img {
opacity: 1;
}
.menu ul li a {
display: inline-block;
text-decoration: none;
color: #555;
font-weight: 500;
transition: 0.5s;
}
.menu ul li:hover a {
color: #ff5d94;
}
i am adding this profile thing in my navbar. navbar is being rendered in App.js
when i click on div
nothing happens. can someone help here?
2
Answers
found a better way to implement drop down (on hover) instead of onclick.
Dropdown.js
style.css
Mistake in handler
It should be:
And dont use class – use className, not directly DOM – use useState hook.
Example:
https://codesandbox.io/s/kind-rgb-wlwlgf