Membangun Aplikasi Penghitung Interaktif
Gabungkan props dan keadaan untuk membangun komponen penghitung dengan tombol tambah, kurang, dan atur ulang yang memperbarui UI secara reaktif.
Membangun Aplikasi Penghitung Interaktif adalah pelajaran React Native Academy gratis di CoddyKit. Ini adalah pelajaran 4 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar React Native Academy, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus React Native Academy mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
Counter App Project Plan
This lesson builds a complete interactive counter app that applies all concepts learned in this course: props for passing data, useState for managing the count, lifted state for sharing between sibling components, and StyleSheet for visual polish. The app will have a display component that shows the current count, three control buttons (Increment, Decrement, Reset), a history log of recent changes, and a step-size selector to change how much each button increments. Planning the component structure before coding prevents confusion.
// Component tree for the Counter App:
// App
// ├── CountDisplay ← shows current count (receives count prop)
// ├── CountControls ← increment/decrement/reset buttons
// │ └── ControlButton ← reusable button component
// ├── StepSelector ← choose step size (1, 5, 10)
// └── HistoryLog ← list of recent operationsSetting Up App State
The App (or screen) component owns all the state: the current count, the step size, and the history log. Because CountDisplay, CountControls, and HistoryLog are siblings that all need different aspects of this state, lifting it to the parent is correct. The history is an array of strings (operation descriptions) that grows with each action. Using a single parent to own all state keeps the logic centralized and easy to follow.
import { useState } from 'react';
export default function CounterApp() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const [history, setHistory] = useState([]);
function addHistory(message) {
setHistory(prev => [message, ...prev].slice(0, 10)); // keep last 10
}
function increment() {
setCount(prev => prev + step);
addHistory(`+${step} → ${count + step}`);
}
function decrement() {
setCount(prev => prev - step);
addHistory(`-${step} → ${count - step}`);
}
function reset() {
setCount(0);
addHistory('Reset → 0');
}
return null; // UI rendered below
}CountDisplay Component
The CountDisplay component is a pure presentational component: it receives the count as a prop and displays it with a dynamic color. Positive counts are green, negative are red, and zero is gray. This is a great example of derived presentation logic — the component doesn't manage state, it just transforms its input prop into visual output. The large number display uses a dramatic font size to make the counter the visual center of attention.
import { View, Text, StyleSheet } from 'react-native';
export default function CountDisplay({ count }) {
const color = count > 0 ? '#2ecc71' : count < 0 ? '#e74c3c' : '#95a5a6';
return (
<View style={styles.container}>
<Text style={styles.label}>Current Count</Text>
<Text style={[styles.count, { color }]}>{count}</Text>
<View style={[styles.bar, { backgroundColor: color }]} />
</View>
);
}
const styles = StyleSheet.create({
container: { alignItems: 'center', paddingVertical: 32 },
label: { fontSize: 14, color: '#999', letterSpacing: 1, textTransform: 'uppercase' },
count: { fontSize: 96, fontWeight: '800', marginVertical: 8 },
bar: { width: 60, height: 4, borderRadius: 2 },
});Reusable ControlButton Component
Build a reusable ControlButton component that accepts a label, an icon, an onPress callback, and a variant ('primary', 'danger', or 'ghost'). The variant determines the button's color scheme. Using a single button component for increment, decrement, and reset avoids duplicating button style code. Each variant maps to a different color set, and the button applies the correct styles automatically based on the prop value.
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
const VARIANT_COLORS = {
primary: { bg: '#4f86f7', text: '#fff', border: '#4f86f7' },
danger: { bg: '#e74c3c', text: '#fff', border: '#e74c3c' },
ghost: { bg: 'transparent', text: '#666', border: '#ddd' },
};
export default function ControlButton({ label, onPress, variant = 'ghost' }) {
const colors = VARIANT_COLORS[variant];
return (
<TouchableOpacity
style={[styles.btn, { backgroundColor: colors.bg, borderColor: colors.border }]}
onPress={onPress}
activeOpacity={0.75}
>
<Text style={[styles.label, { color: colors.text }]}>{label}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
btn: { flex: 1, paddingVertical: 14, borderRadius: 12, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
label: { fontSize: 16, fontWeight: '700' },
});CountControls Layout
The CountControls component renders the three control buttons in a horizontal row. It receives onIncrement, onDecrement, and onReset callback props from the parent. The decrement button uses the 'ghost' variant, increment uses 'primary', and reset uses 'danger'. A flexDirection: 'row' with gap: 10 lays out the three buttons side by side, each taking equal width via flex: 1.
import { View, StyleSheet } from 'react-native';
import ControlButton from './ControlButton';
export default function CountControls({ onIncrement, onDecrement, onReset, step }) {
return (
<View style={styles.row}>
<ControlButton label={`-${step}`} onPress={onDecrement} variant='ghost' />
<ControlButton label='Reset' onPress={onReset} variant='danger' />
<ControlButton label={`+${step}`} onPress={onIncrement} variant='primary' />
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
gap: 10,
paddingHorizontal: 20,
marginBottom: 24,
},
});StepSelector Component
The StepSelector lets users choose how much each button adds or subtracts. It renders a row of step option buttons (1, 5, 10, 25). The currently selected step is visually highlighted. When the user taps a step, it calls the onStepChange callback prop, which updates the step state in the parent App. The parent then passes the new step to CountControls so the button labels update accordingly. This is lifted state in action: the selection lives in the parent, shared between the selector and the controls.
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
const STEPS = [1, 5, 10, 25];
export default function StepSelector({ step, onStepChange }) {
return (
<View style={styles.container}>
<Text style={styles.label}>Step Size</Text>
<View style={styles.row}>
{STEPS.map(s => (
<TouchableOpacity
key={s}
style={[styles.option, s === step && styles.selected]}
onPress={() => onStepChange(s)}
>
<Text style={[styles.optionText, s === step && styles.selectedText]}>
{s}
</Text>
</TouchableOpacity>
))}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { alignItems: 'center', marginBottom: 24 },
label: { fontSize: 13, color: '#999', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 1 },
row: { flexDirection: 'row', gap: 10 },
option: { width: 52, height: 44, borderRadius: 10, borderWidth: 1.5, borderColor: '#ddd', alignItems: 'center', justifyContent: 'center' },
selected: { borderColor: '#4f86f7', backgroundColor: '#4f86f7' },
optionText: { fontSize: 16, fontWeight: '600', color: '#666' },
selectedText: { color: '#fff' },
});HistoryLog Component
The HistoryLog component displays the last 10 operations in a scrollable list. It receives the history array as a prop. Each entry shows an operation description (e.g., '+5 → 15') with a color-coded indicator — green for increments, red for decrements, and orange for resets. Using FlatList handles smooth scrolling if the history fills up. A header shows 'Recent Operations' and a count badge indicates how many operations are recorded.
import { View, Text, FlatList, StyleSheet } from 'react-native';
function EntryColor(text) {
if (text.startsWith('+')) return '#2ecc71';
if (text.startsWith('-')) return '#e74c3c';
return '#f39c12';
}
export default function HistoryLog({ history }) {
if (history.length === 0) return null;
return (
<View style={styles.container}>
<Text style={styles.header}>Recent Operations ({history.length})</Text>
<FlatList
data={history}
keyExtractor={(_, i) => i.toString()}
renderItem={({ item }) => (
<View style={styles.entry}>
<View style={[styles.dot, { backgroundColor: EntryColor(item) }]} />
<Text style={styles.text}>{item}</Text>
</View>
)}
scrollEnabled={false}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { marginHorizontal: 20, padding: 16, backgroundColor: '#f8f9fa', borderRadius: 16 },
header: { fontSize: 13, color: '#999', fontWeight: '600', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 0.5 },
entry: { flexDirection: 'row', alignItems: 'center', paddingVertical: 6, gap: 10 },
dot: { width: 8, height: 8, borderRadius: 4 },
text: { fontSize: 14, color: '#444' },
});Assembling the Full Counter App
Combine all components in the App with the lifted state. The parent holds count, step, and history. It defines the increment, decrement, and reset handler functions that update all three pieces of state atomically. These handlers are passed as callback props to CountControls. The step is passed to both StepSelector (for display) and CountControls (for button labels). The history array is passed to HistoryLog. The entire app's behavior is coordinated from this single parent component.
import { useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet } from 'react-native';
import CountDisplay from './CountDisplay';
import CountControls from './CountControls';
import StepSelector from './StepSelector';
import HistoryLog from './HistoryLog';
export default function CounterApp() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const [history, setHistory] = useState([]);
function addHistory(msg) {
setHistory(prev => [msg, ...prev].slice(0, 10));
}
function increment() { setCount(p => { const n = p + step; addHistory('+'+step+' → '+n); return n; }); }
function decrement() { setCount(p => { const n = p - step; addHistory('-'+step+' → '+n); return n; }); }
function reset() { setCount(0); addHistory('Reset → 0'); }
return (
<SafeAreaView style={styles.safe}>
<ScrollView contentContainerStyle={styles.content}>
<CountDisplay count={count} />
<StepSelector step={step} onStepChange={setStep} />
<CountControls
step={step}
onIncrement={increment}
onDecrement={decrement}
onReset={reset}
/>
<HistoryLog history={history} />
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: { flex: 1, backgroundColor: '#fff' },
content: { paddingBottom: 32 },
});Adding Haptic Feedback
Polish the counter app with haptic feedback using the expo-haptics module. Light haptic on increment, warning haptic on decrement, and a strong notification on reset. Haptic feedback makes the buttons feel more physical and satisfying, significantly improving the tactile experience on real devices. Call the haptic function inside each handler, right before updating state. Haptic feedback is silent when called on simulators — test on a real device to feel the difference.
import * as Haptics from 'expo-haptics';
// Install: npx expo install expo-haptics
function increment() {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
setCount(prev => {
const next = prev + step;
addHistory('+' + step + ' → ' + next);
return next;
});
}
function decrement() {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
setCount(prev => {
const next = prev - step;
addHistory('-' + step + ' → ' + next);
return next;
});
}
function reset() {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
setCount(0);
addHistory('Reset → 0');
}Keyboard Accessibility and usability
Add final accessibility touches to the counter app. Use accessibilityLabel on each button so screen readers announce meaningful descriptions. Use accessibilityState={{ selected: s === step }} on the step selector options to communicate the selected state to assistive technology. Add a accessibilityLiveRegion='polite' to the count display so screen readers announce the new count whenever it changes. These small additions make your app usable by the millions of people who rely on accessibility features on their phones.
// Accessibility additions
// CountDisplay:
<Text
accessibilityLiveRegion='polite'
accessibilityLabel={'Current count: ' + count}
style={[styles.count, { color }]}
>
{count}
</Text>
// ControlButton:
<TouchableOpacity
accessibilityRole='button'
accessibilityLabel={'Increment by ' + step}
onPress={onPress}
style={...}
>
// StepSelector option:
<TouchableOpacity
accessibilityRole='radio'
accessibilityState={{ selected: s === step }}
accessibilityLabel={'Step size ' + s}
onPress={() => onStepChange(s)}
>Persisting the Counter to AsyncStorage
Enhance the counter app by saving the count to AsyncStorage so it survives app restarts. Use useEffect to watch the count value and write it to AsyncStorage whenever it changes. On the first render, read the saved value from AsyncStorage and initialize the count state. This is a minimal but complete example of local data persistence — the same pattern scales to saving user preferences, form drafts, and app configuration. AsyncStorage writes are asynchronous and should not block UI updates.
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';
// npx expo install @react-native-async-storage/async-storage
const COUNT_KEY = '@counter_value';
export default function PersistentCounter() {
const [count, setCount] = useState(0);
const [loaded, setLoaded] = useState(false);
// Load saved count on mount
useEffect(() => {
AsyncStorage.getItem(COUNT_KEY)
.then(stored => {
if (stored !== null) setCount(parseInt(stored, 10));
})
.finally(() => setLoaded(true));
}, []);
// Save count whenever it changes (after initial load)
useEffect(() => {
if (!loaded) return;
AsyncStorage.setItem(COUNT_KEY, count.toString());
}, [count, loaded]);
if (!loaded) return null; // wait for saved value before rendering
return (
<>{/* CountDisplay, CountControls, etc. */}</>
);
}Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: component decomposition breaks a complex screen into focused, reusable pieces, lifted state in the parent component coordinates behavior across sibling components, and callback props + haptic feedback make the counter interactive and tactile. Next up we explore handling user input with TextInput, touch events, and form components.
Belajar JavaScript dengan tutor AI — gratis
Tulis dan jalankan kode asli di browser kamu, dapatkan bantuan instan dari tutor AI 24/7, dan lanjutkan di mana kamu tinggalkan di web atau aplikasi.
- Kursus
- 30
- Pelajaran
- 120
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Membangun Aplikasi Penghitung Interaktif” gratis?
Ya — teks lengkap “Membangun Aplikasi Penghitung Interaktif” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus React Native Academy, upgrade ke CoddyKit PRO. Kursus React Native Academy mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Membangun Aplikasi Penghitung Interaktif”?
Gabungkan props dan keadaan untuk membangun komponen penghitung dengan tombol tambah, kurang, dan atur ulang yang memperbarui UI secara reaktif. Kamu berlatih React Native Academy dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai React Native Academy?
Tidak diperlukan pengalaman sebelumnya. React Native Academy di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 4 dari 4.
Berapa lama pelajaran “Membangun Aplikasi Penghitung Interaktif” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran React Native Academy ini?
Ya. Setiap pelajaran React Native Academy menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Mengirim Data dengan Props
- Mengelola Keadaan Komponen dengan useState
- Mengangkat Keadaan ke Atas
- Membangun Aplikasi Penghitung Interaktif