Swipe Actions is a UI component mostly used on iOS. When you swipe a list item to the left or right, context actions are revealed. For example, in a mail app, it might be "Mark as read" or "Delete".
In this tutorial, we'll learn how you can make such a component for the web, using React and Framer Motion. This component heavily relies on the useSnap hook, which I covered in the last post. Check it out to understand how this hook works and grab its source code at the end of the post.
Our goal is to build a universal SwipeActions component that can be used as a foundation to build other components like these:
Cozy.fm – How to start journaling
Alice
16:25
About your car extended warranty
Try swiping the elements to the left or move focus to them using Tab
The components above use some newer CSS features and might look funky in older browsers. Sorry!
To make everyone's life easier, our component will come unstyled. We'll save some time by not writing styles, and whoever ends up using our component will be able to customize it to their needs. To make it even more flexible, we'll make it composable. So instead of a single <SwipeActions /> component, we'll have the following structure:
If you used Radix Primitives, you know the drill. Our component won't have as elaborate of API as Radix Primitives does (or else you'll be reading this until tomorrow), but the concept is the same.
Before we can start coding, we need to install some modules (besides React, which I assume you have installed already):
clsx and react-merge-refs are small utilities which allow us to combine class names and refs. react-use-motion-measure is a fork of react-use-measure which uses MotionValue's instead of state. This allows us to react to element size changes without re-rendering the whole component.
Create files SwipeActions.tsx and SwipeActions.css and import everything we'll need for this project.
Our component will consist of a few smaller components, and they all need to somehow share state. This is what React Context is for. Our Root component will wrap everything with a context provider, so all children will have access to the central state.
Let's start with the Root component. It will act as a wrapper for other components and will be what ties them together. It will also be the owner of the shared state.
Let's unpack. We start with the actionsWidth state which we need to calculate constraints. You see, we won't allow the user to drag the element uncontrolled, we'll constrain its movement so it just shows the actions underneath. There shouldn't be any movement to the right at all, and for the left side, we use the action's width to allow just the right amount of movement. actionsWrapperInset acts as a small padding to avoid any parts of actions peeking from underneath the trigger.
Next is the useSnap hook. We pass our constraints and snap points based on these constraints. Since we limit movement to the x axis, our snap points will only have the x property, which describes their position inside the constraints box. In our case, it's leftmost when actions are visible ({ x: 0 }) and rightmost when actions are hidden ({ x: 1 }).
And finally, we render children wrapped in div and SwipeActionsContext.Provider with the required state and all the functions.
While our component is unstyled, we still need to add a couple of styles to allow actions to hide under the trigger element. To implement such layout, we'll use the position CSS property. Specifically, we'll set position: relative for the root element, and position: absolute with inset for actions. This will allow actions to take all the available space remaining underneath main content without stretching the container.
Trigger is a component that the user needs to drag to reveal the actions. It doesn't do anything besides passing triggerRef and dragProps from context to the element.
To make sure that trigger always stays on top of actions, we also need to specify its z-index.
And then we have actions. This component acts as a wrapper for action buttons and is used to correctly measure and set constraints for the trigger element.
There are a couple of different things going on. Firstly, we explicitly set height of actions outer wrapper based on trigger height. This is related to differences between Firefox/Safari and Chrome. Those browsers render and measure elements with aspect-ratio differently in some cases when one of the sizes is not set explicitly. Unfortunately, our component would be one of such cases, so we have to set the height explicitly. aspect-ratio is required to make the buttons square like on example components, so we absolutely need it working across browsers.
Secondly, we measure the width of actions and update the state every time it changes. We use state here (instead of MotionValue) because our constraints and snap points depend on actions width, so when it changes, components need to be re-rendered.
Lastly, we handle focus. Usually, div elements can't receive focus, but since focus and blur events in React bubble (unlike their native counterparts), our onFocus and onBlur will be called when any of the children receive or lose focus. This will happen, among other things, when the user navigates with the keyboard and moves focus to one of the actions inside. In this case, we'd like to "open" swipe actions, so the user will see where their focus went. And the same when focus leaves, we close swipe actions to keep the UI tidy.
The styles for the action wrapper are a bit more elaborate than for previous components.
The outer wrapper has absolute positioning (+ we set inset in JavaScript), which makes it take all available space of the parent (Root) element. And we use flex to move the child element to the right edge of the wrapper. The inner wrapper aligns children in a row and is used to measure their total size.
This is only an optional component. You can use Root, Trigger and Actions to build a component that exposes additional info when swiped without any actual actions. And so you won't need the Action component.
But since it's not the main use case and most implementations will have actions inside, this component will come handy. It's just a <button> component with additional behavior on click. When this button is clicked, we call the original onClick handler and check if event.preventDefault() was called. If it wasn't, we'd close the swipe actions and unfocus activeElement (which is our button). It's important to not leave focus inside swipe actions when they are closed, as the browser will fire the focus event again when the user goes to another tab and then back, which will make swipe actions open and look weird.
But if event.preventDefault() was called, we'll assume the user doesn't want the default behavior and will take control over the component from here.
Another important feature of <Action /> is changes to default focus styles. Since our action wrapper has overflow: hidden, the default focus ring will be partly hidden, which isn't user-friendly and looks choppy overall. To fix this, we change the outline offset to be negative, so the outline will be rendered inside the element.
And with that, we're done. All that's left is to pack all the components into one object and export it.
Now you have a reusable Swipe Actions component that you can style however you want. If you want to extend it further, here are a couple of ideas how you can improve it:
Programmatically open swipe actions and/or control state from outside. For example, for desktop users, you might want to display a more conventional "three dots" menu button, which, on click, opens swipe actions. This will tie a familiar pattern to a new component, which eases its adoption.
Add support for swipe actions that swipe to the right. Or maybe even in both directions?
Here is the complete code of the component:
And here is an example of usage:
Published at 19 August 2024
Was this interesting or useful?
I publish a newsletter with articles I found interesting and announces of my new posts. You can leave your email and get new issues delivered to your inbox!
Alternatively you can subscribe to my RSS feed to know about new posts.
Or follow me on Twitter, where I sometimes post about new articles, my pet projects, and web dev in general.
If you really like the article, you can give me monies, and I'll buy myself tasty coffee to write even more.