Getting Started With React Popper

React

02/09/2021


I've found the React Popper documentation to not be very comprehensive. This naturally lead to difficulties implementing the library. Here are my findings to help you get started. ⛑

What you'll quickly realise is that you will have to mostly refer to the base PopperJS documentation instead React Popper. The key is knowing how that documentation translates into React.

usePopper hook

This is undoubtedly the most important part of your Popper component. This is essentially a wrapper of the createPopper constructor function that allows you to configure everything.

The 3rd argument of this hook is an object which can hold up to 3 options, i.e. placement, modifiers and strategy.

JAVASCRIPT
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: "right-start",
modifiers: [{ name: "arrow", options: { element: arrowElement } }]
})

Modifiers

Modifiers are the real meat of this library. They allow you to configure 🔧 the behavior of your Popper, with each modifier being its own object in the modifiers array.

Be careful with using functions inside the configuration as they can cause a loop. Check out more about this in the FAQ section.

As you'd expect, PopperJS already has default behavior for many of these modifiers, e.g. Flip and Prevent Overflow.

Arrow

By default, an arrow ⬆️ is not enabled. A code example of one can be found in the documentation. Most notably, the styling of the arrow and it's placement relative to the Popper is your responsibility.


WRITTEN BY

Code and stuff