Table of Contents
Introduction
Hello Everyone and welcome to this new article, where we are going to build a React Native Wheel Picker Example.
The Wheel Picker can be an alternative to other whats of item selection, depending on your app.
Some apps use Multi Select Dropdown, while other apps use actionsheet Selection.
Our Wheel Picker, can be seen in date picker, where you scroll up and down to select from the date Items.
For our app example, we will build a sample app from which the user can select from a list of Fruits.
Our final result of the app will look like this.
Environment Setup
To use Wheel Picker in our app, we will install a tiny library by @gregfrench.
It’s pretty straight forward to install.
yarn add @gregfrench/react-native-wheel-picker
React Native Wheel Picker Basic Usage
<Picker style={{width: 150, height: 180}}
lineColor="#000000"
lineGradientColorFrom="#008000"
lineGradientColorTo="#FF5733"
selectedValue={selectedItem}
itemStyle={{color:"white", fontSize:26}}
onValueChange={(index) => setSelectedItem(index) }>
{itemList.map((value, i) => (
<PickerItem label={value} value={i} key={i} />
))}
</Picker>
As you can see, the Wheel Picker component takes few props in order to work.
lineColor: to set top and bottom line color (Without gradients)
lineGradientColorFrom: to set top and bottom starting gradient line color
lineGradientColorTo: to set top and bottom ending gradient
selectedValue: The current selected item from the wheel
itemStyle: the list item view styles
onValueChange: callback function when the selectedItem is changed, here we’re updating the selecteditem in the state with the new value.
and finally we’re mapping and rendering the list of items from the state.
Full code
import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import Picker from '@gregfrench/react-native-wheel-picker'
var PickerItem = Picker.Item;
const App = () => {
const [selectedItem, setSelectedItem ] = useState(2);
const [itemList , setItemList ] = useState(['Apple', 'Orange', 'Peach', 'Strawberries', 'Pineapple']);
return (
<View style={styles.container}>
<Picker style={{width: 150, height: 180}}
lineColor="#000000"
lineGradientColorFrom="#008000"
lineGradientColorTo="#FF5733"
selectedValue={selectedItem}
itemStyle={{color:"white", fontSize:26}}
onValueChange={(index) => setSelectedItem(index) }>
{itemList.map((value, i) => (
<PickerItem label={value} value={i} key={i} />
))}
</Picker>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex:1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff4646'
}
})
Final Result
Conclusion
And there you have it an sample react native wheel picker app,
I hope you enjoyed reading this article and found it as informative as you have expected.
You can check the source code on github and expo.io.
Stay safe and happy coding.