React Native Academy · Lezione

Creazione di un’app contatore interattiva

Combini props e stato per creare un componente contatore con pulsanti di incremento, decremento e ripristino che aggiornano reattivamente l’interfaccia.

Lezione 4 di 413 passaggi

Creazione di un’app contatore interattiva è una lezione React Native Academy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento React Native Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso React Native Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 operations

Setting 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.

Gratis per iniziare

Impara JavaScript con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
30
Lezioni
120

Domande Frequenti

La lezione «Creazione di un’app contatore interattiva» è gratuita?

Sì — il testo completo di «Creazione di un’app contatore interattiva» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso React Native Academy, passa a CoddyKit PRO. Il corso React Native Academy include 4 lezioni in totale.

Cosa imparerò in «Creazione di un’app contatore interattiva»?

Combini props e stato per creare un componente contatore con pulsanti di incremento, decremento e ripristino che aggiornano reattivamente l’interfaccia. Eserciti React Native Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare React Native Academy?

Non è richiesta alcuna esperienza precedente. React Native Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Creazione di un’app contatore interattiva»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione React Native Academy?

Sì. Ogni lezione React Native Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Passaggio dei dati con le props
  2. Gestione dello stato dei componenti con useState
  3. Sollevamento dello stato
  4. Creazione di un’app contatore interattiva
← Torna a React Native Academy