Horizontal scroll in React Native
Hello friends, I hope you are doing well and building awesome stuff by following this series. In the previous article, we learned about Flexbox in react native and built some cards arranged in a row. Now it's time to learn what if we add more cards to the row. Let's see that in this blog.
I tried to add 3 more cards in the FlatCards.tsx
file and it gave me the below result:
I can see all cards but the cards are shrunk. To keep the appearance of cards as it is we need to make them scrollable. How we can do this?
So friends I have created a new file ScrollableCards.tsx
and created 7 cards in it. Here if you look I am using ScrollView instead of View. Pretty much it has the same styling as of the FlatCards.tsx
file with some minor differences.
import { ScrollView, StyleSheet, Text, View } from 'react-native'
import React from 'react'
export default function ScrollableCards() {
return (
<View>
<Text style={styles.heading}>ScrollableCards</Text>
<ScrollView style={styles.container}>
<View style={styles.card}>
<Text>1</Text>
</View>
<View style={styles.card}>
<Text>2</Text>
</View>
<View style={styles.card}>
<Text>3</Text>
</View>
<View style={styles.card}>
<Text>4</Text>
</View>
<View style={styles.card}>
<Text>5</Text>
</View>
<View style={styles.card}>
<Text>6</Text>
</View>
<View style={styles.card}>
<Text>7</Text>
</View>
</ScrollView>
</View>
)
}
const styles = StyleSheet.create({
heading: {
fontSize: 40,
paddingHorizontal: 10
},
container: {
padding: 8
},
card: {
flex: 1,
backgroundColor: 'grey',
alignItems: 'center',
justifyContent: 'center',
height: 100,
width: 100,
borderColor: '#23C4ED',
borderWidth: 1,
borderRadius: 5,
margin: 10,
}
})
Our app is looking something like this with the above code. (Don't forget to bring the ScrollableCards
component in the App.tsx
file).
The above app is vertically scrollable. Remember by default, the ScrollView container scrolls its components and views in the vertical direction.
You can see from the code that here we are not using flex for container and that's why we are getting all cards in vertical column. So what can we use to align cards in a row and make them scrollable?
To scroll horizontally, ScrollView
uses the props horizontal={true} or we can even use only horizontal. These props may have the value as false as well.<ScrollView horizontal={true} style={styles.container}>
With the above change, our app will look like the one below having a horizontal scroll for ScrollableCards
view.
Friends, try to implement the horizontal scroll in your app. I will catch you up in our next article. Till then keep learning and keep building the awesome stuff.
Special thanks to Hitesh Choudhary !!!