DEV Community

superoverflow
superoverflow

Posted on • Updated on

Making a Dropdown

I was trying to make a dropdown button with React. It turns out to be more tricky than I first thought 🤯.

After discussing with my React Si-Fu @_denb , I finally managed to make a prototype. Below are the libraries I need to use.

  • downshift: a base library for making a dropdown.
  • react-useportal: a library to move the dropdown items to the end of body
  • react-popper: a library to fix the position of the dropdown items
Step 1: make a dropdown menu

  • It is already a dropdown-ish component. However, you will notice when the dropdown list opens, it pushes the content below it down. This is not ideal.
Step 2: adding in Portal

  • now, if the dropdown list open, it is appended at the end. This is still not what we want
Step 3: adding in Popper

  • finally, the dropdown list open, it is rendered below the dropdown button on top of the text. This is what we want. However, the dropdown items still doesn't align with the dropdown button (It will if you resize the window). I think this is because the component reference is set up before rendering and thus confused Popper for the sizing
Step 4: fixing alignment issue after resizing window

  • Now, I tried to use useState instead of useRef. It seems to solve the initial alignment issue
What's next?

I hope to add a transition components wrapper next to make it look even better✌🏻

Top comments (0)