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.