How to get selected value from a select input in React Native
Key takeaways
React Native provides two types of components for handling form data: uncontrolled and controlled components.
Use uncontrolled components for internal state management. The
Pickerhandles its value internally, without React control.Use controlled components for React-managed state such as
useStateto synchronize the component's state with user interactions.Choose controlled components for complex forms and validation; opt for uncontrolled for simpler selections.
React Native is a popular framework for building cross-platform mobile applications using JavaScript and React. When dealing with forms and user interactions, developers often encounter the need to retrieve the selected value from a dropdown, especially when the options are dynamically generated using mapping. We will explore two approaches to get selected values from a select input: uncontrolled components and controlled components in React Native.
Handling form state in React Native
Similar to React, React Native recommends letting components handle form data. The two main types of components in this context are:
Uncontrolled components
Controlled components
Uncontrolled dropdown component
An uncontrolled component in React Native is one where React does not control the state. Instead, the value is managed by the underlying components and the native environment. In the following example, the Picker component's selected value is not managed by React's state or props. It does not explicitly track or control the selected value.
import React from "react";
import { Picker } from "react-native";
export default function App() {
// Uncontrolled component
return (
<Picker>
<Picker.Item label="Red" value="red" />
<Picker.Item label="Green" value="green" />
<Picker.Item label="Blue" value="blue" />
</Picker>
);
}Code explanation
Lines 1–2: We import React and the necessary components from React Native.
Lines 4–13: We create an uncontrolled
Pickercomponent with dynamically generatedPicker.Itemelements.
Controlled dropdown component
A controlled component in React Native, similar to React, is one where the state controls how the component handles form data. The component renders a form, and as the user interacts with it, the data inputted is controlled by the component's state.
import React, { useState } from "react";
import { Picker, View, Text, StyleSheet } from "react-native";
const App = () => {
const [value, setValue] = useState('');
const handleChange = (itemValue) => {
setValue(itemValue);
};
return (
<View style={styles.container}>
<Picker
selectedValue={value}
onValueChange={(itemValue) => handleChange(itemValue)}
>
<Picker.Item label="Red" value="red" />
<Picker.Item label="Green" value="green" />
<Picker.Item label="Blue" value="blue" />
</Picker>
{value !== '' && (
<Text style={{ marginTop: 20, fontSize: 18 }}>
Selected Value: {value}
</Text>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
export default App;Code explanation
Lines 1–2: We import React and specific components (
useState,Picker,View,Text,StyleSheet) from thereact-nativelibrary.Line 6: We use the
useStatehook to create a state variablevalueand its updater functionsetValue. The initial state is set to an empty string.Lines 8–10: We define the
handleChangefunctionitemValueas a parameter and update thevaluestate with the new value.Lines 12–21: We return JSX code to render the component. The component is enclosed within a
Viewcomponent, and aPickercomponent is used to create a dropdown menu. ThreePicker.Itemcomponents represent the options:Red,Green, andBlue.Lines 23–27: Conditional rendering is used to display a
Textcomponent below thePickeronly if a value is selected (i.e.,value !== ''). The text displays the selected value.Lines 32–38: We define a StyleSheet using the
StyleSheet.createmethod. The styles include setting the main container (container) with flex properties, aligning items at the center, and justifying content there.Line 40: We export the
Appcomponent as the default export, making it accessible for use in other application parts.
Developers can choose between uncontrolled and controlled components based on their specific use case and application requirements.
Conclusion
Dropdowns in forms play a significant role in enhancing user interaction by offering a streamlined, user-friendly way to select options from a predefined list. They simplify the selection process and even save space by hiding a long list of options until a user needs to make a selection.
Controlled components in React manage form data through state, ensuring synchronization between the UI and state, making them suitable for form validation and complex forms with interdependent fields. Uncontrolled components handle form data via the DOM, offering simplicity for basic forms. Each type has its advantages based on the form's complexity and requirements.
Free Resources