StyleSheet.create
- React Native course
- Beginner
- Lesson 31/116
- 5 min
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.
Practice 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>.
Starter code
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function Card() {
// Return a View with styles.card
return null;
}
// Add the card style with StyleSheet.create hereSample 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' }
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pass styles.card to the style prop
<View style=____>
<Text>Hi</Text>
</View>
<View style={styles.card}>
<Text>Hi</Text>
</View>
Explanation: styles.card is a reference; embed it in braces inside JSX.
2 Why prefer StyleSheet.create?
const styles = StyleSheet.create({
card: { padding: 12 }
});- It is shorter than inline objects
- It compiles styles once and compares faster Correct answer
- It only works in dark themes
- It produces a CSS file
Explanation: StyleSheet.create turns styles into references and boosts performance.
3 Match each term to its description
| Term | Meaning |
|---|---|
StyleSheet.create |
Defines styles once |
styles.card |
Reference to a defined style |
style prop |
The prop that styles a component |
camelCase |
Property name format |