How to Make Custom DropDown in React Native?
Nov 28, 2022 . Admin
In this tutorial, We will create to a custom dropdown in react native.you can easily make to create a custom dropdown in react native app.
In this example, we will without use react native library in this react native app. we will create to common file for the customer dropdown and then use to app.js file.you can at the time one select to the dropdown. below this example.
Step 1: Download ProjectIn the first step run the following command to create a project.
expo init ExampleAppStep 2: Images.js
In this step we will create to common Images.js file in react native project.
export const Images = { arrow_drop_down:require('././assets/arrow_drop_down.png'), }Step 3: DropDown.js
In this step, You will open the DropDown.js file and put the code.
import { Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native' import React from 'react' import { Images } from './Images' const DropDown = ({ data, selectValue, oneSelect }) => { const [option, setOption] = React.useState(false); const selectOption = () => { setOption(!option) } const oneSelectItem = (val) => { setOption(false) oneSelect(val) } return ( <View style={{ }}> <TouchableOpacity style={styles.dropDownStyle} onPress={selectOption} > <Text>{!!selectValue ? selectValue.name : 'Choose Option'}</Text> <Image source={Images.arrow_drop_down} style={{ transform: [{ rotate: option ? "0deg" : "180deg" }] }} > </Image> </TouchableOpacity> {option && ( <View style={styles.openDropDown}> {data.map((val, i) => { return ( <TouchableOpacity onPress={() => oneSelectItem(val)} style={{ ...styles.optionName, backgroundColor: val.id == selectValue.id ? 'pink' : 'yellow' }} > <Text >{val.name}</Text> </TouchableOpacity> ) })} </View> )} </View> ) } const styles = StyleSheet.create({ dropDownStyle: { backgroundColor: '#eab676', minHeight: 40, borderRadius: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', padding:5, width:'100%', }, openDropDown: { backgroundColor: 'red', padding: 10, marginVertical: 5 }, optionName: { margin: 5, padding: 10, borderRadius: 4 } }) export default DropDownStep 4: App.js
In this step, You will open the App.js file and put in the code.
import React, {useState} from 'react'; import {Modal, Text, TouchableHighlight, View} from 'react-native'; import DropDown from './DropDown.js'; const App = () => { const [selectValue, setSelectValue] = React.useState(""); const data = [ { id: 1, name: 'user' }, { id: 2, name: 'Admin' }, { id: 3, name: 'employee' }, ]; const selected = (item) => { setSelectValue(item) } return ( <View style={{ marginTop: 50 }}> <DropDown selectValue={selectValue} data={data} oneSelect={selected} > </DropDown> </View> ); }; export default App;Step 5: Run Project
In the last step run your project using the below command.
expo start
You can QR code scan in Expo Go Application on mobile.
Output:
It will help you...