code

A Simple Draggable Carousel that supports React Router

I am currently working on a project to create a React-based kiosk application framework for use in the GLAM sector. It’s intended to help bootstrap the creation of digital interactive displays.

As part of this project I need a carousel component. There are dozens of these out there, but none quite fitted what I needed:

  • look and feel natural when used on a large screen (e.g. 42 inch)
  • No styling
  • Be able to wrap any kind of component, without extra markup
  • support React Router

I found a lot that are very well written and supported, but the few that supported drag actions used CSS3 transformations and frames which just didn’t feel natural. The ones that used physics based libraries were too complicated for what I needed, and made it hard to integrate React Router.

In the projects I worked on while at Te Papa The Museum of New Zealand, we found through observation that given a touch screen most people will attempt to swipe, drag and zoom. If you visit Te Papa you’ll see some screen with a navigation, but that also support swipe.

In order to track usage via analytics – both swipe and touch/click events – the simplest course of action is to use routes for each page or piece of content. Hence my requirement to support integration with React Router.

One of the other requirements was for the direction of movement when the navigation links were used to reflect the order of the content. If you click on home, while on page 3 the content will slide off to the right past pages 2 and one to get to home. If you go to page 2 from home, the content will slide off to the left and past page 1.

The Routable Carousel component is part of a bigger project, but you are welcome to lift it (please add a hat-tip link back in the file if you do ūüôā ).

Using the component is simple. Just add your pages like so:

<RoutableCarousel>
  <Home path={"/"} />
  <PageOne path={"/page-one"} />
  <PageTwo path={"/page-two"} />
  <PageThree path={"/page-three"} />
</RoutableCarousel>

The component uses the excellent react-spring and react-use-gesture libraries and is a functional component that uses hooks extensively. You’ll also need to copy over any of the dependencies.

Happy to get feedback here, or via github issues.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s