Marcelo Gadotti
Marcelo Gadotti

Reputation: 17

Update value using onScroll event from ScrollView on React Native

I'm trying to update/get values inside ScrollView, like this follow code:

<SafeAreaView style={styles.container}>
  <ScrollView
    contentContainerStyle={{ flexGrow: 1 }}
    style={styles.scrollView}
    onScroll={(event) => {
      const currentOffset = event.nativeEvent.contentOffset.y;
      urlx = currentOffset > 100 ? url1 : url2;
      log(urlx);
    }}
  >
    <Text>{urlx}</Text>
  </ScrollView>
</SafeAreaView>;

Text doesn't update with the new urlx value when the scroll event happens.

How to force this update from Text?

Upvotes: 0

Views: 497

Answers (1)

spatak
spatak

Reputation: 1379

Just put urlx in the component's state:

const [urlx, setUrlx] = useState()

Then update urlx like this:

<SafeAreaView style={styles.container}>
  <ScrollView
    contentContainerStyle={{ flexGrow: 1 }}
    style={styles.scrollView}
    onScroll={(event) => {
      const currentOffset = event.nativeEvent.contentOffset.y;
      urlx = currentOffset > 100 ? url1 : url2;
      setUrlx(urlx) // here
    }}
  >
    <Text>{urlx}</Text>
  </ScrollView>
</SafeAreaView>;

The reason you have to use useState is because on state update, react will take care of updating your component with new value

Upvotes: 1

Related Questions