Styles and StyleSheet
A web developer opens Sprout's code, looks for a .css file, and finds none. Styling in React Native is written in JavaScript, attached with a style prop. The property names look familiar, but the rules around them are simpler and stricter than CSS.
The rule
Styles are JavaScript objects: camelCase names, unitless numbers, no cascade.
import { StyleSheet, View, Text } from 'react-native';
const styles = StyleSheet.create({
card: {
padding: 16,
borderRadius: 12,
backgroundColor: '#eef7ee',
},
name: {
fontSize: 20,
fontWeight: '600',
},
thirsty: {
backgroundColor: '#fff3e0',
},
});
<View style={[styles.card, needsWater && styles.thirsty]}>
<Text style={styles.name}>{plant.name}</Text>
</View>Each part of the rule:
- JavaScript objects. A style is an object.
StyleSheet.creategroups them and checks the property names in development. Plain inline objects also work, but named styles keep code tidy. - camelCase names.
background-colorbecomesbackgroundColor;font-sizebecomesfontSize. - Unitless numbers.
padding: 16means 16 density-independent pixels, which look the same physical size on phones with different screens. There is nopx,remorem. Percentages are written as strings:width: '50%'. - No cascade. There are no selectors, no classes and no inheritance from parents, apart from nested
Textinheriting text styles. Each component gets exactly the styles you give it.
Style arrays combine styles. Later entries win, and falsy values such as false are skipped. That is how needsWater && styles.thirsty adds an orange background only when needed.
Some CSS does not exist: no hover (phones have no mouse), no media queries (use the useWindowDimensions hook instead), and shorthand strings like margin: '8px 16px' are not allowed. Use marginVertical and marginHorizontal.
The shortcut
Translate any CSS rule in three moves: drop the hyphen and capitalise (font-size → fontSize), drop the unit (16px → 16), and quote anything that is not a plain number ('50%', 'bold', '#fff').
The CSS
.name { font-size: 20px; font-weight: bold; margin: 0 8px; }
Drills
Answer fast — trust the rule.
How is the CSS background-color: white written in React Native?
What does padding: 16 mean?
In style={[styles.card, styles.thirsty]}, both set backgroundColor. Which wins?
When needsWater is false, what happens to [styles.card, needsWater && styles.thirsty]?
Remember
- Styles are JavaScript objects: camelCase names, unitless numbers, no cascade.
- Translate CSS in three moves: camelCase, drop units, quote non-numbers.
- Trap: shorthand strings, hover and media queries do not exist here.
