Search code examples
javascriptreact-nativescrollview

Enlarging single item in React Native ScrollView


I have a ScrollView like so:

        <ScrollView>
          {this.state.businessMerchants.map(merchant => (
            <Business
              merchant={merchant}
              key={merchant.id}
            />
          ))}
        </ScrollView>

Usually with 2-4 items in it.

I want to highlight the currently top item and make it take up more room (maybe 10% more?). This "top item" would switch as one scrolls through the list.

Is there a more standardized way of doing this, or will I have to do something like use scrollEventThrottle and a custom function like so?

Pseudocode below:

if((findHeightOfItem + padding) * multiple === itemPos) {
addSizeHere()
}

Quite curious about what's the best/most performative way of doing this in React Native.


Solution

  • Steps:

    • Decide the height of each component itemHeight
    • Apply onScroll and get current scrolled height scrolledHeight
    • Have one local state called currentItemIndex which will be decided in onScroll function and will be calculated as Math.floor(scrolledHeight / itemHeight)
    • Send isCurrentItem as prop to Business component
    • Apply necessary styles to Business component depending on value of boolean isCurrentItem
    • I would suggest you to use Animated view with transform scale

      handleScroll = (e) => {
        const currentHeight = e.nativeEvent.contentOffset.y;
        const currentItemIndex = Math.floor(currentHeight / 100);
        this.setState({ currentItemIndex });
      }
      
      <ScrollView onScroll>
        {this.state.businessMerchants.map((merchant, index) => (
          <Business
            merchant={merchant}
            isCurrentItem={index === this.state.currentItemIndex}
            key={merchant.id}
          />
        ))}
      </ScrollView>