Search code examples
javascriptreactjsreact-nativecircular-slider

Creating a circular slider in React Native


I am wanting to create a circular slider in React Native for a project of mine. Although I am not entirely sure on how to create one. Could someone help me out?

Here is a little sketchup of what I want it to look like:

I did some searching on the interwebs and found some posts about circular sliders in React Native. But these posts seem to be dated and the projects linked/provided in these posts would not work for me.

1. https://stackoverflow.com/questions/51058669/react-native-circular-slider
2. https://stackoverflow.com/questions/38253804/how-to-make-a-circular-slider-in-react-native


Note: I am fairly new to the world of React and React Native but do have decent experience with JavaScript. Right now I am still learning about React and React Native.


Solution

  • Your best best is probably svg via react-native-svg, since that will allow you to declaratively draw and animate arbitrary shapes without having to write platform-specific native code.

    Note that setting up react-native-svg is slightly different if you are working with expo or have ejected, which may explain why some of those older examples you mentioned don't work (they pre-date expo).

    Drawing with SVG is generally straight-forward, although you will need to use arc's in paths, which is about as awkward as SVG gets (but still not too bad).

    The trickiest parts of a circular slider are capturing the touch input with PanResponder and converting coordinates between cartesian (x,y) coordinates of the touch input and polar (angle,distance) coordinate systems in order to know where to move the slider to.

    In your case it looks like you want to lock the movement of the slider to specific increments around the clock so you'll also need to find the nearest increment to the polar-coord of the current touch, but that should be easy in polar coords - just find the increment with the closest angle to that of the touch.

    Here is an Expo project that illustrates the slider part. It looks like this:

    enter image description here