React Native Reanimated Switch

Karthik Balasubramanian
Timeless
3 min readSep 1, 2020

--

Let us build a switch component from scratch.

3D Render by Udhaya Chandran

Tools used :

  • React Native
  • React Native Reanimated
  • Figma

Design level dissection of Switch Component

The on and off states of Switch designed by Fayas fs

The components are:

  1. A rectangle with a border-radius.
  2. A circle placed absolute inside it.

Let us have a look at the measurements :

The rectangle dimensions are
50 x 28 with a border-radius of ~36.5px.

The circle has dimensions of
24 x 24 with a fully rounded border-radius.

Setting up React Native Project.

(Skip to next section, if already done..)

Go ahead to this link https://reactnative.dev/docs/environment-setup#docsNav and follow the steps on creating a new react native project.

npx react-native init RNSwitch

To start the application run npx react-native run-ios inside your React Native project folder. Open your project in VS Code and head to the file named App.js.And remove the code under the return statement and replace it with:

return {
<>
<View>
</View>
<>
}

You have successfully finished creating a project.

Let us start coding now. 💃

The Switch Component will look like this :

For developers getting confused and going like, “What is exactly happening here?”. Let us break it down.

Component Structure

  1. Pressable

Pressable is a Core Component wrapper that can detect various stages of press interactions introduced in the latest version of React Native v0.63.0.

This wraps our Animated View which has the dimensions of 50 x 28.

2. Animated View — Rectangle

3. Animated View — Absolute Positioned Circle

Animations Breakdown

  1. Translating the absolute positioned circle on changing the switch state.

It is a super simple smooth Spring Animation.

spring(switchTranslate, {toValue: 0, // Initial for switchState false and 22 for truemass: 1,damping: 15,stiffness: 120,overshootClamping: false,restSpeedThreshold: 0.001,restDisplacementThreshold: 0.001,}).start();

2. Interpolating the switch track color when the Circle View translates.

const interpolateBackgroundColor = {backgroundColor: interpolateColors(switchTranslate, {     inputRange: [0, 22],     outputColorRange: [inActiveTrackColor, activeTrackColor],    }),};

This is a cool interpolation function that is imported from the react-native reanimated library.

The color of the track goes from inActiveTrackColor to activeTrackColor when the switchTranslate value animates to 0 and 22.

So there you go we have our own simple Switch Component where the animations happen in the UI thread.

Let us see how it looks in iOS and Android.

Woah that looks beautiful 🎉 .

This is Karthik representing Timeless.

You can find the repo here and an npm package here.

If you find this blog post helpful, share it with a friend.

If you find any difficulties please feel free to add your comments.

--

--