How to populate react-native picker dynamically with values from an API

Alex
5 min readMay 2, 2020

This tutorial will explain how to populate a react-native picker dynamically with values from an API.

The first step is to create a react-native project (I usually have sub folders in my downloads folder where I create these projects to keep things organised) using the below command. Before entering the command though I would usually open up my code editor and enter the command in the terminal of that editor.

react-native init rnpickeproject

Once you have ran this and the project has been created, start your simulator with the below command (the first time this command is ran it may take a few minutes, so go and make a cup of tea while the simulator is loading!)

react-native run-ios

Once your simulator has loaded, go back to your code editor you will see a file called “App.js”, inside of it is a class named “App” remove all of its content and replace it with the below

class App extends React.Component {render() {return (<View style={{marginTop:50}}><View><Text style={{ textAlign: 'center' }}>My picker App!</Text></View></View>)}}

This is just a basic template for our page.

The API we will be retrieving information from is a fake data API, more information can be found below.

Ok, so the first thing we need to do is create a state object which will contain an array that will hold the values for our dropdown as well as a state value for the currently selected dropdown list item.

Write something like the below (Outside of the render and return method but inside of the class)

state = {userValues:[],
selectedValue:''
}

The next step is to install the react native community picker package using the below.

npm install @react-native-community/picker --save

The reason for this is that the original picker is depreciated. Once you have installed this you will need to install the pods for this as well. You can do this by entering the command below in your terminal.

cd ios && pod install

This will change directory to your “ios” folder and install any pods dependencies. You may need to close your simulator and metro bundler to see this installation take effect though.

Next, we want to create a method which we will run on the load of the component, lets call it “GetFakeData”, in here we will be making a call to the API using fetch and setting the state after getting the response from the API.

The endpoint i will be using is: https://jsonplaceholder.typicode.com/users, this just retrieves 10 users with some fake information. So currently our method looks like the below. We use a promise to convert the response to json and can also handle an error callback, however, we also set the state value equal to the value of the response in json format.

GetFakeData = () => {fetch('https://jsonplaceholder.typicode.com/users').then(response => response.json()).then(json => {console.log(json)this.setState({userValues:json})})}

To ensure our endpoint is returning data I have entered a console.log so it prints out the data on the developer tools in the browser. If you want to debug your app, make sure the simulator is open and click “cmd” + D ( on mac) to open a menu, see screenshot below.

Click the word “Debug”, this will open a new tab in your default browser, open the developer tools of the browser (I am using Chrome so i click the 3 vertical dots on the right side of the window, then click “more tools”, finally, I then click “Developer tools”, then click on the “console” tab.

We now need to call this method on load of the component using the lifecycle method “componentDidMount”.

componentDidMount() {this.GetFakeData()}

Furthermore, we now need to loop over the state object and return the information that we want to extract and show on the picker. To do this we will create an array using the “map” method to return a Picker item with a label and unique index that is currently stored in our state because we retrieved the values from the API.

To do this we will create a “let” variable inside the render method but outside of the return method which will map over the current state and pass in the current value and index to the map callback function.

let myUsers = this.state.userValues.map((myValue,myIndex)=>{console.log('myValue: ' + myValue.name)return()})

So as you can see I have a return statement in there but it is blank, we will now put a picker item inside of the return and set its label to “myValue.name” and “myValue.username” because “name” and “username” are the keys that are used in the object returned from the API and “myValue” is the current value we use to access this.

So now our variable looks like the below.

let myUsers = this.state.userValues.map((myValue,myIndex)=>{return(<Picker.Item label={myValue.name + ' - ' + myValue.username} value={myIndex} key={myIndex}/>)});

Now that we have created a variable of an array that will contain our picker items we need somewhere to show these items, hmmm, I wonder how we could do this?

Well, we are in luck, we will simply use the “Picker” component from react-native community in our render method, the code is below.

<Picker selectedValue={this.state.selectedValue} onValueChange={(value)=>this.setState({selectedValue:value})} >{myUsers}</Picker>

What we are doing is using our variable “myUsers” which contains an array of picker items as we looped over them all earlier and just slotting that variable in between the opening and closing picker tags with curly brackets on either side of the “myUsers” variable, so when we refresh our app we will see a picker populated with values from the API like below.

Within the opening “Picker” tag we are setting the current selected value equal to the state object “selectedValue”, we do this as on the in built method on the Picker called “onValueChange” we set the state value of “selectedValue” equal to the newly selected value when we scroll on the dropdown.

There we have it, that is how we populate a react native picker dynamically from an API, i hope you learned something from this, if there is anything i can do to improve my explanations please say so and I will try my best to improve and please share/clap this article as that helps out tremendously!

Have a great day!

See my blog — https://simplyreact.uk/

--

--