Categories
JavaScript Answers React Native Answers

How to add horizontal ScrollView snapping with React Native?

Spread the love

Sometimes, we want to add horizontal ScrollView snapping with React Native.

In this article, we’ll look at how to add horizontal ScrollView snapping with React Native.

How to add horizontal ScrollView snapping with React Native?

To add horizontal ScrollView snapping with React Native, we can set the snapToAlignment prop to 'center'.

For instance, we write:

import * as React from 'react';
import { Text, View, ScrollView } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  return (
    <View>
      <ScrollView
        horizontal
        decelerationRate={0}
        snapToInterval={200}
        snapToAlignment="center">
        {Array(100)
          .fill()
          .map((_, i) => (
            <Text
              key={i}
              style={{
                width: 100,
                height: 100,
                backgroundColor: 'green',
                margin: 10,
              }}>
              {i}
            </Text>
          ))}
      </ScrollView>
    </View>
  );
}

to add the horizontal prop to make the ScrollView scroll horizontally.

And we set snapToAlignment to 'center' to make the ScrollView snap element in the center of the screen.

Conclusion

To add horizontal ScrollView snapping with React Native, we can set the snapToAlignment prop to 'center'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *