Ali Zeynalov
Ali Zeynalov

Reputation: 3017

react-native fill the picker by mapping

on my RN project, I'm trying to fill my Picker by mapping from the state, which is an array. I consoled the object during mapping and it seems there isn't any problem, it shows the object that is being mapped. What I am doing wrong? Can you help me, please?

<Item>
                        <Picker
                                iosHeader="Select one"
                                mode="dropdown"
                                onValueChange={this.onBranchChange.bind(this)}>
                                {this.state.branchAddresses.map((address,i) =>
                                     {
                                         console.log("myAddresses: ",address);
                                         return <Item style={{fontFamily: 'SourceSansPro-Regular'}} label={address.id} value={address.id} key={i}/>}
                                )}
                            </Picker>
                        </Item>

And here is the snapshot of console.log().It writes the objects without any problem.enter image description here

enter image description here

Here is the warning that I get. enter image description here enter image description here

Upvotes: 0

Views: 5477

Answers (2)

You should use ..!

import React, { useState, useEffect } from 'react';
import {

  StyleSheet,
  View
} from 'react-native';
import axios from 'axios'
import { Picker } from '@react-native-picker/picker';

export default function App() {

  const [state, setState] = useState([]);

  const fetchAPI = () => {
    const result = axios.post('http://www.example.com')
      .then(response => {
        const data = JSON.parse(JSON.stringify(response)).data.listaIncidencia;
        setState(data)
      })
      .catch(error => {
        console.error(error);
      });
    return result;
  };
  useEffect(() => {
    fetchAPI();
  }, []); 
  const [selectedValue, setSelectedValue] = useState("DEFAULD");

  console.log(selectedValue)
  return (
    <View>
      <Picker
        selectedValue={selectedValue}
        onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}>{
          state.map((item, index) => {
            return <Picker.Item value={item.idMotivo} label={item.motivoDesc} key={index} />
          })
        }
      </Picker>
    </View>
  );
}

Upvotes: 1

Tobias Lins
Tobias Lins

Reputation: 2651

You should use the Item from the Picker component to get this work.

There are two possible ways to do it.

const PickerItem = Picker.Item;

and than using this <PickerItem> component later on.

Or you just use the Component directly

<Picker.Item style={{fontFamily: 'SourceSansPro-Regular'}} label={address.id} value={address.id} key={i}/>

Upvotes: 2

Related Questions