I'm sure there is a way to do this, but I just can't see how yet.
What I'd like to do, is add a Picker component, but rather than hard-code the list of items, fetch this from a service and have the Picker bound to something I can populate later.
Here's what I have, but my app won't even run now. Any ideas please?
'use strict'; var React = require('react-native'); var { Picker, Text, View } = React; var AvailableServices = React.createClass({ getInitialState() { var fetchServicesUri = 'http://some.url/available_services'; fetch(fetchServicesUri) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); var services = []; for(var service in responseJson.services) { services.push(<Picker.Item label={service.Label} value={service.Value}/>); } this.setState({ services: services }); }) .catch((error) => { console.warn(error); }) .done(); return { services: [], selectedService: null } }, render() { return ( <View> <Text>Pick a service</Text> <Picker selectedValue={this.state.selectedService} onValueChange={(service) => this.setState({selectedService:service})} > {this.state.services} </Picker> </View> ); } }); module.exports = AvailableServices;
Using the react-native-picker-select component Kindly consider the code below: import React from "react"; import RNPickerSelect from "react-native-picker-select"; import { StyleSheet, Text, View } from "react-native"; export default function App () { return ( <View style={styles. container}> <Text>Hello World!
Here is my implementation: import DropDownPicker from "react-native-dropdown-picker"; import { View } from "react-native"; const Test = () => { return ( <View> <DropDownPicker items={[ { label: "Item 1", value: "item1" }, { label: "Item 2", value: "item2", selected: true }, ]} onChangeItem={(item) => console.
You should probably set up your initial state as the empty array, then call your service on componentWillMount or componentDidMount. I've set up something that works with some dummy data here, and pasted the code below.
'use strict'; var React = require('react-native'); var { Picker, Text, View, AppRegistry } = React; var PickerItem = Picker.Item; var SampleApp = React.createClass({ getInitialState() { return { services: ['a', 'b', 'c', 'd', 'e'], selectedService: 'a' } }, componentDidMount() { setTimeout(() => { this.setState({ services: [ 'one', 'two', 'three', 'four', 'five' ] }) }, 3000) }, render() { let serviceItems = this.state.services.map( (s, i) => { return <Picker.Item key={i} value={s} label={s} /> }); return ( <View> <Text>Pick a service</Text> <Picker selectedValue={this.state.selectedService} onValueChange={ (service) => ( this.setState({selectedService:service}) ) } > {serviceItems} </Picker> </View> ); } }); AppRegistry.registerComponent('SampleApp', () => SampleApp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With