React Native Reanimated Switch
Let us build a switch component from scratch.
Tools used :
- React Native
- React Native Reanimated
- Figma
Design level dissection of Switch Component
The components are:
- A rectangle with a border-radius.
- 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
- 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
- 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 🎉 .