Styling Patterns

Article · 2:00

StyleSheet.create, per-platform differences, a dark mode that works, and where NativeWind fits.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Styles are plain objects. StyleSheet.create wraps them, and its value today is not performance - it is that it type-checks the keys and gives you an error for a typo that an inline object would silently ignore. The style prop also takes an array, and later entries win, which is how a base style and a conditional override are combined.

Platform differences are real and small. Platform.OS is a string you can branch on, and Platform.select reads better when a value differs per platform - a shadow on iOS is shadowColor and friends, while Android uses elevation, and you want both. Files named Button.ios.tsx and Button.android.tsx are resolved automatically when the difference is a whole component rather than a value.

Dark mode comes from useColorScheme, which returns 'light' or 'dark' and re-renders when the system setting changes. Define your colours once as a pair of objects and select between them; hard-coded hex values scattered through components are how an app ends up with white text on a white background in dark mode.

NativeWind brings Tailwind's class names to React Native, compiling them to the same style objects at build time. If your team already thinks in Tailwind it is a real productivity gain. If not, StyleSheet is not the thing slowing you down.

TS Example 1 45 lines
import { StyleSheet, Platform, useColorScheme, View, Text } from 'react-native';

const palette = {
  light: { bg: '#ffffff', text: '#111827', card: '#f3f4f6' },
  dark: { bg: '#0b1220', text: '#f9fafb', card: '#1f2937' },
};

export function Card({ title }: { title: string }) {
  // Re-renders when the system setting changes - no listener to wire up.
  const scheme = useColorScheme() ?? 'light';
  const colors = palette[scheme];

  return (
    <View style={{ flex: 1, backgroundColor: colors.bg, padding: 16 }}>
      {/* An array: base style first, overrides after. Later entries win. */}
      <View style={[styles.card, { backgroundColor: colors.card }]}>
        <Text style={[styles.title, { color: colors.text }]}>{title}</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    borderRadius: 12,
    padding: 16,
    // The same visual effect, expressed differently on each platform.
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOpacity: 0.12,
        shadowRadius: 8,
        shadowOffset: { width: 0, height: 2 },
      },
      android: { elevation: 3 },
      default: {},
    }),
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    // A one-off platform branch, where a whole select would be noise.
    marginTop: Platform.OS === 'android' ? 2 : 0,
  },
});

Open this example in the editor and change it. Nothing you type is saved.