Styles and StyleSheet
React Native has no CSS files. A style is a JavaScript object passed to the style prop. Property names are almost the same as in CSS, only in camelCase: backgroundColor instead of background-color.
The StyleSheet object
Styles are usually collected at the bottom of the screen file with StyleSheet.create:
// app/index.tsx
import { StyleSheet, Text, View } from 'react-native';
export default function Index() {
return (
<View style={styles.container}>
<Text style={styles.title}>My tasks</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
padding: 16,
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#222',
},
});The screen shows a grey strip with a large bold heading. StyleSheet.create returns the same object, but the editor suggests property names and marks typos right away.
Numbers without units
Sizes are plain numbers without px. These are density-independent pixels: 16 looks the same on a regular screen and on a very sharp one. Percentages are strings: width: '50%'.
| CSS | React Native |
|---|---|
font-size: 18px | fontSize: 18 |
margin: 0 16px | marginHorizontal: 16 |
padding: 8px 0 | paddingVertical: 8 |
border: 1px solid #ddd | borderWidth: 1, borderColor: '#ddd' |
border-radius: 8px | borderRadius: 8 |
There are no shorthands like border or margin: 0 16px; each property is set separately.
Several styles at once
You can pass an array to style. Properties from the right override the left ones, and false and null are skipped:
// components/TaskItem.tsx
import { StyleSheet, Text } from 'react-native';
export default function TaskItem({ title, done }: { title: string; done: boolean }) {
return <Text style={[styles.task, done && styles.done]}>{title}</Text>;
}
const styles = StyleSheet.create({
task: { fontSize: 18, paddingVertical: 8 },
done: { color: '#999', textDecorationLine: 'line-through' },
});Create a components folder in the project root and this file inside it. Render the component on the screen: <TaskItem title="Buy bread" done /> shows a grey struck-through line, and with done={false} a regular one.
Almost no inheritance
On the web, the font color set on body is inherited by every element. In React Native styles are not inherited: color on a View does not affect the Text inside it. The exception is a nested Text, which takes the font and color from the outer Text.
Common mistake
Writing units or CSS names:
// app/index.tsx
// Wrong:
const styles = StyleSheet.create({
title: { 'font-size': '24px' },
});Such a style is ignored, and TypeScript reports an error. Write fontSize: 24, camelCase and a number.