React Native - Picker


Advertisements


In this chapter, we will create simple Picker with two available options.

Step 1 − Create File

Here, the src/components/home/Home.js folder will be used as a presentational component.

src/components/home/Home.js

import React, { Component } from 'react'
import PickerExample from './PickerExample.js'

const Home = () ⇒ {
   return (
      <PickerExample />
   )
}
export default Home

Step 2 - Logic

this.state.user is used for picker control.

The updateUser function will be triggered when a user is picked.

src/components/home/PickerExample.js

import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'

class PickerExample extends Component {
   state = {user: ''}
   updateUser = (user) ⇒ {
      this.setState({ user: user })
   }
   render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
               <Picker.Item label = "Steve" value = "steve" />
               <Picker.Item label = "Ellen" value = "ellen" />
               <Picker.Item label = "Maria" value = "maria" />
            </Picker>
            <Text style = {styles.text}>{this.state.user}</Text>
         </View>
      )
   }
}
export default PickerExample

const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
   }
})

It will show the following output −

React Native Picker

Advertisements