React Native
horizontal
Learn horizontal scrolling with the horizontal prop.
The horizontal prop
The horizontal prop makes ScrollView scroll horizontally. The default value is false, so ScrollView scrolls vertically; setting horizontal flips it to left and right.
You write it as <ScrollView horizontal> or <ScrollView horizontal={'{true}'}>. The short form horizontal alone means true; this is a JSX shortcut.
In horizontal mode each child's width comes from its content. For a fixed card width you set width in style. We will detail that in the next lesson.
Horizontal ScrollView and width
In a horizontal ScrollView, the cards you line up take width from their content. That can look uneven. To fix it, you give each child a width through style.
For example style={'{ width: 160 }'} makes the card a fixed 160 pixels wide. The cards stay aligned as you scroll; this is useful for galleries.
In horizontal scroll, contentContainerStyle lets you add gap or paddingHorizontal between cards so they do not stick to the edges.
Exercise Write a horizontal card gallery
Put three <View> cards inside a horizontal ScrollView. Each card should be styled with width: 120 and height: 120, with a <Text> inside.
Show example solution
const styles = { card: { width: 120, height: 120, margin: 8, backgroundColor: '#eee' } };
function App() {
return (
<ScrollView horizontal>
<View style={styles.card}><Text>One</Text></View>
<View style={styles.card}><Text>Two</Text></View>
<View style={styles.card}><Text>Three</Text></View>
</ScrollView>
);
}
export default App;
Test yourself
-
Add horizontal scrolling
import { ScrollView, Text } from 'react-native';
function App() {
return (
<ScrollView ____>
<Text>Card one</Text>
<Text>Card two</Text>
</ScrollView>
);
}
Show answer
import { ScrollView, Text } from 'react-native';
function App() {
return (
<ScrollView horizontal>
<Text>Card one</Text>
<Text>Card two</Text>
</ScrollView>
);
}
-
What does the horizontal prop do?
- Flips the scroll direction to horizontal
- Increases the scroll speed
- Changes the background color
- Hides the content
Show answer
Changes the background color — horizontal ScrollView scrolls left and right.
-
Match horizontal scroll concepts
- horizontal
- Enables horizontal scroll
- width
- Fixes the card width
- gap
- Space between cards
- vertical
- Default direction
Next lesson: contentContainerStyle