horizontal
- React Native course
- Beginner
- Lesson 60/116
- 4 min
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.
Practice 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.
Starter code
import { ScrollView, View, Text } from 'react-native';
// write the horizontal gallery hereSample 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;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add horizontal scrolling
import { ScrollView, Text } from 'react-native';
function App() {
return (
<ScrollView ____>
<Text>Card one</Text>
<Text>Card two</Text>
</ScrollView>
);
}
import { ScrollView, Text } from 'react-native';
function App() {
return (
<ScrollView horizontal>
<Text>Card one</Text>
<Text>Card two</Text>
</ScrollView>
);
}
Explanation: the horizontal prop turns on horizontal scrolling.
2 What does the horizontal prop do?
- Flips the scroll direction to horizontal
- Increases the scroll speed
- Changes the background color Correct answer
- Hides the content
Explanation: horizontal ScrollView scrolls left and right.
3 Match horizontal scroll concepts
| Term | Meaning |
|---|---|
horizontal |
Enables horizontal scroll |
width |
Fixes the card width |
gap |
Space between cards |
vertical |
Default direction |