Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native foreach loop

I'm developing a little app in React Native and I am looking for something like a foreach function. I just can't find a foreach loop. Not on StackOverflow and not even in the docs. I've found something with 'map', but I don't know if this is what I'm looking for.

With a request to my Server I get multiple objects of users. When I log the result, it looks like this:

Object {
    "id": "1",
    "role": "user",
    "username": "user1",
  },
Object {
    "id": "2",
    "role": "admin",
    "username": "user2",

I'd like to output this to a list. In plain PHP I would use a foreach loop for this, but like I said, I can't find a foreach loop for React Native.

How is it possible to loop trought this objects? I know that I could also use a simple for loop, but this would definitly not be my first choice...

EDIT: I saved this value in this.state.users with this.setState({users: responseData.users});. State is defined in my constructor. I try to access this with this.state.users.map(id => <Text>{id}</Text>) but I always get the same error: null is not an object (evaluating 'this.state.users.map'). Am I doing this right?

like image 225
Tekk Avatar asked Aug 24 '17 12:08

Tekk


People also ask

What is forEach in react native?

The forEach() method can be used to iterate over an array outside of your JSX code in React. If you need to iterate over an array and render its elements directly in your JSX code, use the map() method instead.

How do you loop through an array of objects in react native?

To loop through an array of objects in React:Use the map() method to iterate over the array. The function you pass to map() gets called for each element in the array. The method returns a new array with the results of the passed in function.

How do you use loop in react native?

To loop and render elements in React Native, we can use the JavaScript array map method. to call arr. map with a callback to return the Text component with the entry a as the text. We set the key prop to a unique value for each entry so that React can identify the rendered components.


2 Answers

You can use map or for-of or any other

Example:

// for of
for (let userObject of this.state.users) {
    console.log(userObject.username);
}
// map
this.state.users.map((userData) => {
    console.log(userData.username);
});

as per the error you may not have data within users state, so you are getting error. If data is proper then above example will work properly

like image 75
Jigar Shah Avatar answered Sep 17 '22 22:09

Jigar Shah


In react, preferred way is map method of Array. Example using ES6 arrow function:

render() {    
    return (
        <View>    
           {dataList.map(r => <Button>{r}</Button>)}    
        </View>
    )
}
like image 27
Ozgur Avatar answered Sep 18 '22 22:09

Ozgur