Styling & Flexbox di Mobile — Mobile

Styling di React Native React Native tidak pakai CSS file. Semua styling melalui JavaScript objects via StyleSheet.create(). Propertinya mirip CSS tapi pakai…

Styling di React Native

React Native tidak pakai CSS file. Semua styling melalui JavaScript objects via StyleSheet.create(). Propertinya mirip CSS tapi pakai camelCase dan tanpa unit (nilai angka = dp/density-independent pixels).

StyleSheet.create

import { StyleSheet, View, Text } from 'react-native';

export default function Card() {
  return (
    <View style={styles.card}>
      <Text style={styles.title}>Card Title</Text>
      <Text style={styles.desc}>Description here</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    // Shadow (iOS)
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    // Shadow (Android)
    elevation: 3,
  },
  title: {
    fontSize: 18,
    fontWeight: '600',
    color: '#1a1a1a',
  },
  desc: {
    fontSize: 14,
    color: '#666',
    marginTop: 4,
  },
});

Flexbox di Mobile — Default Berbeda!

// Di Web CSS: flex-direction default = row
// Di React Native: flexDirection default = column!

// Ini artinya children disusun vertikal secara default
<View style={{ flex: 1 }}>
  <Text>Atas</Text>
  <Text>Tengah</Text>
  <Text>Bawah</Text>
</View>

// Untuk horizontal layout:
<View style={{ flexDirection: 'row', gap: 8 }}>
  <Text>Kiri</Text>
  <Text>Tengah</Text>
  <Text>Kanan</Text>
</View>

Perbedaan CSS vs React Native Styling

Responsive Design

import { Dimensions, useWindowDimensions } from 'react-native';

// Hook (recommended, auto-update saat rotasi)
function MyComponent() {
  const { width, height } = useWindowDimensions();
  const isTablet = width >= 768;

  return (
    <View style={{ flexDirection: isTablet ? 'row' : 'column' }}>
      <View style={{ flex: isTablet ? 1 : undefined }}>
        <Text>Sidebar</Text>
      </View>
      <View style={{ flex: isTablet ? 2 : undefined }}>
        <Text>Content</Text>
      </View>
    </View>
  );
}

Yang akan kamu pelajari