The style Prop and StyleSheet

+15 Mana ✨

If you have written inline styles in React for the web, the style prop in React Native will look familiar: it takes an object whose keys follow CSS property names in camelCase, such as backgroundColor. React Native has no CSS files to fall back on, though, and one style prop accepts several objects at once. Which value wins when those objects overlap matters as soon as you build a component with its own defaults that each screen can adjust.

Key terms

  • StyleSheet.create: a function that defines a component's named styles in one object, such as styles.card.
  • StyleSheet.flatten: a function that merges an array of styles into one object, where a later entry overrides an earlier one.
  • StyleProp<T>: the TypeScript type for a style prop, which accepts a style object of type T, false, null, undefined, an empty string, or an array of any of these, nested arrays included.

Most core components take a style prop

A settings card, styled with inline objects:

tsx
<View style={{backgroundColor: '#ffffff', borderRadius: 8, padding: 12}}>
  <Text style={{fontSize: 16, fontWeight: 'bold'}}>Notifications</Text>
</View>

Most core components accept style, and its values usually match CSS the way the names do. Button is one exception: it has no style prop, and you change its look through its color prop.

The last style in an array wins

Pass an array to style and React Native applies its entries from first to last. When two entries set the same property, the later value replaces the earlier one, and a property that only one entry sets is kept as it is:

tsx
<Text style={[styles.amount, {color: '#d70015'}]}>Payment failed</Text>

If styles.amount sets fontSize, fontWeight and color, this text keeps that size and weight and turns red.

StyleSheet.flatten merges by the same rule and hands back the result, which is handy when you want to see what an array resolves to:

tsx
const styles = StyleSheet.create({
  card: {backgroundColor: '#ffffff', borderColor: '#c7c7cc', borderWidth: 1, borderRadius: 8, padding: 12, marginBottom: 8},
  highlighted: {borderColor: '#0a84ff', borderWidth: 2},
});

StyleSheet.flatten([styles.card, styles.highlighted]);
// returns {backgroundColor: '#ffffff', borderColor: '#0a84ff', borderWidth: 2, borderRadius: 8, padding: 12, marginBottom: 8}

Arrays also keep conditional styles short. StyleProp allows false in an array, and StyleSheet.flatten skips every entry that is null or not an object, so the condition can sit right inside the array:

tsx
<View style={[styles.row, isSelected && styles.selectedRow]} />

While isSelected is false, the second slot holds false, and the row keeps its base style.

Naming styles with StyleSheet.create

Once a component has several styled elements, inline objects crowd the JSX. A StyleSheet.create call below the component moves the styles out of the render function and leaves the markup easier to follow.

The function is an identity function: it returns the object you pass in, so styles.card is the object you wrote. What you gain is static type checking, because its TypeScript signature checks each named style against the native style properties and returns a read-only object with the same keys. In development it also freezes each named style to prevent mutation. Treat the result as constant data and build variations with arrays rather than editing it.

Accepting a style from the parent

A reusable component can accept a style prop from its parent and pass it on to the element it renders. That gives you a cascade like the one CSS has: the parent sets the margin or color for one particular use, and the component keeps its own defaults for everything else.

Order matters here as well. Put the component's own styles first and the parent's style last, so the parent's values replace the defaults wherever both set a property. Type the prop as StyleProp<ViewStyle>, or StyleProp<TextStyle> for a style you hand to a Text. Both types are exported from react-native. Because StyleProp allows nested arrays and StyleSheet.flatten walks into them, a parent can pass one object or a whole array and it still fits inside yours.

The Card in the code example below the lesson takes a title, an optional highlighted flag and a style prop, and builds its array in that order:

tsx
<View style={[styles.card, highlighted && styles.highlighted, style]}>

The Drafts card sets highlighted, so it gets the thicker blue border. The Archive card passes style={{backgroundColor: '#e5e5ea'}}, which comes last, so it replaces the white background from styles.card and leaves the card's border, radius and padding alone. The Inbox card passes neither, which makes highlighted false and style undefined, and both slots drop out of the merge.

Code Examples

tsx
import {StyleSheet, Text, View} from 'react-native';
import type {StyleProp, ViewStyle} from 'react-native';

type CardProps = {
  title: string;
  highlighted?: boolean;
  style?: StyleProp<ViewStyle>;
};

export function Card({title, highlighted = false, style}: CardProps) {
  return (
    <View style={[styles.card, highlighted && styles.highlighted, style]}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
}

export default function MailboxList() {
  return (
    <View>
      <Card title="Inbox" />
      <Card title="Drafts" highlighted />
      <Card title="Archive" style={{backgroundColor: '#e5e5ea'}} />
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: '#ffffff',
    borderColor: '#c7c7cc',
    borderWidth: 1,
    borderRadius: 8,
    padding: 12,
    marginBottom: 8,
  },
  highlighted: {
    borderColor: '#0a84ff',
    borderWidth: 2,
  },
  title: {
    fontSize: 16,
    fontWeight: 'bold',
  },
});
✓ Completed