React Native Segmented Control
For devs coming here in 2021, Thank you :) I have updated the package to Typescript now. Check it out here.
Let us try to build a Segmented Control with React Native.
You can also find an updated npm package here for the same with the Dark mode feature.
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 RN-SegmentedControl
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.
Go ahead and create the files:
src/components/segmentedControl
This is our component that will render the Segmented Control.
It accepts the following props :
- tabs: An Array of String, Labels for the segments
- onTabPress: A callback function returning the index of the segment clicked.
- currentIndex (Optional): Index value for setting the active segment. Defaults to 0.
- segmentedControlBackgroundColor (Optional): Background color of the segmented control.
- activeSegmentBackgroundColor (Optional): Background color of active segment.
- textColor (Optional): Color of segment label.
- activeTextColor (Optional): Color of active segment label.
So here we basically styled our segmented control using flex and rendered all the labels.
We have positioned an absolute View, which indicates the active segment, which will translate based on the segment label clicked.
The animation here is quite simple. We translate the absolute View-based on the number of Segments.
const translateValue = ((width - 4) / props?.tabs?.length
This value is multiplied by the active tab index value which gives the translateX value.
{transform: [ { translateX: tabTranslate } ]}
So this gives a neat animation while changing the segments.
src/appRoot/index.js
In this file, we just render our component and customize it based on our needs.
Now head to App.js
and render <AppRoot/>
.
We would see something like this.
Looks nice !! Let us see how the animation works.
It works a treat !!
Let us try to run the project in Android now.
Ooops. We have a problem...
Let us go ahead and this style to the textWrapper
object.
elevation: 9
Now the screen would look like:
So we now have a Custom Segmented Control for both Android and iOS.
Happy coding !!
If you find this useful, do check out my blog on iOS-like Search Component.