The StyleSheet API in React Native provides a powerful and efficient way to manage styles. It ensures that your styles are defined in one place and can be reused across multiple components.
StyleSheet.create
, which takes an object where the keys are style names and the values are style definitions.style
prop.Consider the course list screen of “JUST-Learning.” Each course card needs consistent styling for layout, text, and images.
import React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
const CourseCard = ({ course }) => {
return (
<View style={styles.card}>
<Image source={{ uri: course.image }} style={styles.image} />
<Text style={styles.title}>{course.title}</Text>
<Text style={styles.description}>{course.description}</Text>
</View>
);
};
const styles = StyleSheet.create({
card: {
backgroundColor: '#fff',
borderRadius: 8,
shadowColor: '#000',
shadowOpacity: 0.2,
shadowRadius: 4,
padding: 16,
marginVertical: 8,
},
image: {
width: '100%',
height: 150,
borderRadius: 8,
marginBottom: 8,
},
title: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
marginBottom: 4,
},
description: {
fontSize: 14,
color: '#666',
},
});
export default CourseCard;
In this lesson, you explored the StyleSheet API, learning how to create and apply styles in a structured manner. Using StyleSheet.create
helps keep your styles organized and optimized for performance.