Ad

Use For Loop In Flatlist React Native

I'm beginner in react native, and I want to use for loop in flatlist to push require data,

    render() {
  return (
  <View style={styles.container}>
  <FlatList
  data={[
  require("./assest/image1.jpg"),
  require("./assest/image2.jpg"),
  require("./assest/image3.jpg"),
  ]}
  renderItem={({ item }) => {
  return <ListItem image={item} />
  }}
  keyExtractor={
  (index) => {return index}
  }
  />
  </View>
  )
}
}

Like when pushing array from state using for loop

  state ={
  a: [12 , 13 , 14 ,15 , 19 ,21 ]
b: "1"
d = () => {
let c =[];
for (var i =0; i<= this.state.a.length - 1 ; i++) {
c.push( <child text = {this.state.a[i] />);
}
return c;
};

Is there anyway to use looping in flatlist or we can't using any looping in list or flatlist in React Native.

Ad

Answer

You can define a state (array) and then loop through your required data and push them into the array state. Then, pass that state into the dataprop of the FLatlist.

You can do something like this...

import React, { Component } from 'react';
import { View, FlatList } from 'react-native';
import ListItem from '...'; //import the ListItem here

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentDidMount = () => {
    let data = [];

    const images = {
      image1: require("./assest/image1.jpg"),
      image2: require("./assest/image2.jpg"),
      image3: require("./assest/image3.jpg"),
    }

    images.forEach(image => {
      data.push(image);
      this.setState({ data })
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={({ item }) => {return <ListItem image={item} />}}
          keyExtractor={(index) => {return index}}
        />
      </View>
    );
  }
}

Here, when the component mounts, it loops through the 'images' object and push them into an array called 'data' and store it to the state. Then, that state is passed to the Flatlist as a prop.

Please go through this and ask me if you have any further questions regarding this.

Ad
source: stackoverflow.com
Ad