React Native
Summary - Style
Combine StyleSheet, color and spacing to write a business card.
Summary - Style
In this group you learned four things. The style prop gives a component an inline object or a StyleSheet.create reference. color, fontSize, fontWeight shape text. padding sets inner space, margin outer space. borderWidth, borderColor, borderRadius draw a border.
Now you will combine them into a real business card component: the name big and bold, the phone number under it, the box bordered with inner space. Two short tasks lead you there.
Exercise Business card skeleton
Write a BusinessCard component. Define card and name styles with StyleSheet.create. card: padding: 16, borderWidth: 1, borderColor: 'gray', borderRadius: 8. name: fontSize: 20, fontWeight: 'bold'. The component returns a <View style={styles.card}> containing <Text style={styles.name}>Alex</Text>.
Show example solution
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function BusinessCard() {
return (
<View style={styles.card}>
<Text style={styles.name}>Alex</Text>
</View>
);
}
const styles = StyleSheet.create({
card: { padding: 16, borderWidth: 1, borderColor: 'gray', borderRadius: 8 },
name: { fontSize: 20, fontWeight: 'bold' }
});
Exercise Add a phone to the card
Add a phone style to the previous skeleton: color: 'gray', marginTop: 4. Inside <View style={styles.card}>, below the name, also include <Text style={styles.phone}>555 123 45 67</Text>.
Show example solution
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
export default function BusinessCard() {
return (
<View style={styles.card}>
<Text style={styles.name}>Alex</Text>
<Text style={styles.phone}>555 123 45 67</Text>
</View>
);
}
const styles = StyleSheet.create({
card: { padding: 16, borderWidth: 1, borderColor: 'gray', borderRadius: 8 },
name: { fontSize: 20, fontWeight: 'bold' },
phone: { color: 'gray', marginTop: 4 }
});
Test yourself
-
Best way to reuse a style in many places?
// Same card style repeated in 50 components
- Write an inline object in each component
- Define it once with StyleSheet.create
- Recreate the object on every render
- Give up on styling
Show answer
Define it once with StyleSheet.create — StyleSheet.create defines once; the reference is reused.
-
Match each style property to its job
- StyleSheet.create
- Defines styles once
- padding
- Inner space
- borderRadius
- Corner rounding
- fontWeight: 'bold'
- Bold text
Next lesson: flexDirection