React Native
StyleSheet.create
Learn style objects with StyleSheet.create.
StyleSheet.create
Recreating inline objects on every render hurts performance. Instead you define styles once with StyleSheet.create and name them: const styles = StyleSheet.create({ card: { padding: 12 } });.
You pass the named style with style={styles.card}. This reads better and lets React Native compile styles into a reference number for faster comparisons. The same style can be reused across many components.
Define and use
Using styles in a component takes two steps. First, gather all styles at the bottom of the file with const styles = StyleSheet.create({ ... }). Then reference them inside the component as style={styles.card}.
Naming is free but should be meaningful: card, title, row, container. You can also pass an array of styles: style={[styles.card, styles.highlight]}. The rightmost style overrides the left.
Exercise Write a card with StyleSheet
Write a Card component. Define a style named card with StyleSheet.create: { padding: 12, backgroundColor: 'white' }. The component returns a <View style={styles.card}> containing <Text>Card</Text>.
Show example solution
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function Card() {
return (
<View style={styles.card}>
<Text>Card</Text>
</View>
);
}
const styles = StyleSheet.create({
card: { padding: 12, backgroundColor: 'white' }
});
Test yourself
-
Pass styles.card to the style prop
<View style=____>
<Text>Hi</Text>
</View>
Show answer
<View style={styles.card}>
<Text>Hi</Text>
</View>
-
Why prefer StyleSheet.create?
const styles = StyleSheet.create({
card: { padding: 12 }
});
- It is shorter than inline objects
- It compiles styles once and compares faster
- It only works in dark themes
- It produces a CSS file
Show answer
It compiles styles once and compares faster — StyleSheet.create turns styles into references and boosts performance.
-
Match each term to its description
- StyleSheet.create
- Defines styles once
- styles.card
- Reference to a defined style
- style prop
- The prop that styles a component
- camelCase
- Property name format
Next lesson: Color and font