0

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

1 Answer 1

0

I would recommend you to separate your drop down to a component in a sperate file. Also check out scss

So you could set a single function where you pass the value of the selected item when the item is clicked. for example

onClick={(e) => onSelect(e, item?.value)}

check out this code sandbox example, I continued from where you left in your code, https://codesandbox.io/s/react-dropdown-forked-d6w6zq?file=/src/DropDown.js:950-991

Hope this helps!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.