El componente ScrollView permite crear una vista que se puede desplazar (hacer scroll) ya sea de forma vertical o horizontal.
Ideal cuando tienes muchos elementos y no caben en la pantalla.
import { ScrollView, View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<ScrollView style={styles.scrollView}>
<View style={styles.boxPink}>
<Text>Sección 1</Text>
</View>
<View style={styles.boxBlue}>
<Text>Sección 2</Text>
</View>
<View style={styles.boxGreen}>
<Text>Sección 3</Text>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
scrollView: {
flex: 1,
padding: 10,
backgroundColor: '#f9f9f9',
},
boxPink: {
height: 200,
backgroundColor: 'pink',
marginBottom: 10,
justifyContent: 'center',
alignItems: 'center',
},
boxBlue: {
height: 200,
backgroundColor: 'skyblue',
marginBottom: 10,
justifyContent: 'center',
alignItems: 'center',
},
boxGreen: {
height: 200,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
},
}); ScrollView por defecto scroll vertical.FlatList o SectionList por rendimiento.ScrollView horizontal permite desplazarse de forma horizontal. Para activarlo, usa la propiedad horizontal={true}.
Esto es útil para crear carruseles o listas horizontales.
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import { ScrollView, View, StyleSheet } from 'react-native';
export default function HorizontalScrollExample() {
return (
<SafeAreaProvider>
<SafeAreaView style={styles.safeArea}>
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
contentContainerStyle={styles.container}
>
{COLORS.map((color, index) => (
<View
key={index}
style={[styles.card, { backgroundColor: color }]}
/>
))}
</ScrollView>
</SafeAreaView>
</SafeAreaProvider>
);
}
const COLORS = [
'red', 'blue', 'green', 'orange', 'purple', 'teal', 'gold', 'pink',
];
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center', // centra en la pantalla si hay poco contenido
},
container: {
paddingHorizontal: 16,
paddingVertical: 20,
},
card: {
width: 150,
height: 150,
marginRight: 12,
borderRadius: 12,
elevation: 4, // para sombra en Android
shadowColor: '#000', // para sombra en iOS
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.3,
shadowRadius: 4,
},
}); Para desactivar la barra de desplazamiento en horizontal, usa:
showsHorizontalScrollIndicator={false}
| Propiedad | Descripción |
|---|---|
horizontal | Permite activar el scroll horizontal. Por defecto es false. |
showsVerticalScrollIndicator | Oculta o muestra la barra vertical (true o false). |
showsHorizontalScrollIndicator | Lo mismo pero para la barra horizontal. |
contentContainerStyle | Estilos aplicados al contenido interno, no al contenedor. |
onScroll | Función que se ejecuta mientras haces scroll. |