Home > Back-end >  For loop inside Scrollview
For loop inside Scrollview

Time:06-05

I try to run the create new feature as many times as the size of my array is, unfortunately I fail.

Main element code

return (
      <View
        style={{
          flex: 1,
          alignContent: "center",
          alignItems: "center",
        }}
      >
        <Text
          style={{
            fontSize: 20,
            margin: 30,
            color: colors.darkGray,
          }}
        >
          ──────── Skanowane kody ────────
        </Text>
        <ScrollView>
         
        {newHistoryScan(images.qr_test, text[0])}

        </ScrollView>
      </View>
    );
  }

A function that renders the next item

function newHistoryScan(image, result) {

  return (
    <View
      style={{
        alignItems: "center",
      }}
    >
      <Image
        source={image}
        resizeMode="contain"
        style={{
          width: 350,
          height: 150,
        }}
      />
      <TouchableOpacity
        onPress={() => {checkResult(result)}}
        >
        <Text
          style={{
            color: 'blue',
            fontSize: 20,
            marginTop: 10,
            marginBottom: 40,
          }}
        >
          {result}
        </Text>
        </TouchableOpacity>
    </View>
  );
}

So, I made a function that works, it displays all the items from the array, unfortunately when I call the newHistoryScan function, the screen on the phone remains white, the items do not appear.

function loopItems(){
    for (let a = 0; a < text.length; a   ){
      console.log(text[a])
      newHistoryScan(images.qr_test, text[a])
  }
}

Console MS Code Console

Phone Empty screen - phone

If I paste the reference to the newHistoryScan function there, the items are displayed on the phone.

working screen - phone

Calling a function that displays elements sequentially and should call this function the number of times

<ScrollView>
         
      {loopItems()}

        </ScrollView>

Correctly working (direct) function call.

<ScrollView>
         
        {newHistoryScan(images.qr_test, text[a])}

        </ScrollView>

CodePudding user response:

I think your issue is that loopItems doesnt return anything. To achieve this with a for loop you would do this:

function loopItems(){
    const items = []
    for (let a = 0; a < text.length; a   ){
      console.log(text[a])
      items.push(
        newHistoryScan(images.qr_test, text[a])
      )
    }
    return items
}

I think you should use map instead:

 function loopItems(){
   // NOTE: I have no idea where you initialize text or images
   return text.map(item=>{
      console.log(item);
      return newHistoryScan(images.qr_test, item);
  })
}
  • Related