I'm trying to develop a React Dropdown from scratch. What's missing here in my component is that it's not showing the selected item from the dropdown. I know that I'm missing some logic for dropdown-items to show them. Please guide me how to add that logic. My code looks like following:
import * as React from "react";
import user_circle_black from "./assets/icons/user_circle_black.svg";
import "./App.css";
const App = () => {
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(!open);
};
const handleMenuOne = () => {
// do something
setOpen(false);
};
const handleMenuTwo = () => {
// do something
setOpen(false);
};
return (
<div className="dropdown">
<button onClick={handleOpen}>Dropdown</button>
{open ? (
<ul className="menu">
<li className="menu-item">
<button onClick={handleMenuOne} className="dropdown-menu">
<img src={user_circle_black}></img>
<p>Menu 1</p>
</button>
</li>
<li className="menu-item">
<button onClick={handleMenuTwo} className="dropdown-menu">
<img src={user_circle_black}></img>
<p>Menu 2</p>
</button>
</li>
</ul>
) : null}
</div>
);
};
export default App;
Here is the code for styling:
.dropdown {
position: relative;
}
.dropdown-menu {
display: flex;
align-items: center;
gap: 0.5rem;
}
.menu {
position: absolute;
list-style-type: none;
margin: 5px 0;
padding: 0;
border: 1px solid grey;
width: 150px;
}
.menu > li {
margin: 0;
background-color: white;
}
.menu > li:hover {
background-color: lightgray;
}
.menu > li > button {
width: 100%;
height: 100%;
text-align: left;
background: none;
color: inherit;
border: none;
padding: 5px;
margin: 0;
font: inherit;
cursor: pointer;
}
And this the codesnadbox example for this: https://codesandbox.io/s/react-dropdown-z07tye?file=/src/App.js:0-1064