Ad

RN - How To Get Label From Slider?

- 1 answer

I want to get the picker's label chosen by the user and store it in this.state.name, I coded the following but the 'value' is being saved instead. How to get the label?

    <Picker
      selectedValue={this.state.name}
      style={{height: 50, width: 100}}
      onValueChange={(label) => this.setState({name: label})}
      >
      <Picker.Item label="Juan" value="key0" />
      <Picker.Item label="Pedro" value="key1" />
      <Picker.Item label="David" value="key2" />
    </Picker>
Ad

Answer

Pass items as an array of objects and it can be done easily.

    import * as React from 'react';
import { Text, View, StyleSheet, Picker } from 'react-native';
import Constants from 'expo-constants';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      pickerArray: [
        { label: 'Juan', value: 'key0' },
        { label: 'Pedro', value: 'key1' },
        { label: 'David', value: 'key2' },
      ],
    };
  }
  render() {
    return (
      <View style={styles.container}>
        {this.state.name !== '' && (
          <Text style={styles.texto}>
            Se ha seleccionado a {this.state.name}
          </Text>
        )}

        <Picker
          selectedValue={this.state.value}
          style={[styles.picker]}
          itemStyle={styles.pickerItem}
          onValueChange={person => {
            var selectedObj = this.state.pickerArray.find(person1 => {
              return person1.value === person;
            });
            console.log(selectedObj);
            if (selectedObj) {
              this.setState({ name: selectedObj.label,
              value : selectedObj.value
              });
            }
          }}>
          {this.state.pickerArray.map(person => {
            return <Picker.Item label={person.label} value={person.value} />;
          })}
        </Picker>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    alignItems: 'center',
    padding: Constants.statusBarHeight,
    backgroundColor: 'white',
  },
  picker: {
    width: 200,
    height: 44,
    backgroundColor: '#FFF0E0',
    borderColor: 'red',
    borderBottomWidth: 2,
    flex: 90
  },
  pickerItem: {
    height: 44,
    color: 'white'
  },
  texto: {
    fontSize: 30,
    color: 'red',
  }
});
Ad
source: stackoverflow.com
Ad