Events in React Native

Events zijn gebruikersinteracties zoals klikken, typen, of swipen. In React Native gebruik je event handlers om op deze acties te reageren.

Belangrijkste events:

  • onPress - Wanneer gebruiker op iets tikt
  • onChangeText - Wanneer tekst verandert in een input
  • onSubmitEditing - Wanneer gebruiker op Enter drukt
  • onFocus - Wanneer input focus krijgt
  • onBlur - Wanneer input focus verliest

Button Component

De Button component is de simpelste manier om een klikbare knop te maken.

Basis Gebruik

import { Button } from 'react-native';

export default function App() {
  const handlePress = () => {
    console.log('Button is geklikt!');
  };

  return (
    <Button 
      title="Klik hier" 
      onPress={handlePress}
    />
  );
}

Button met Kleuren

<Button 
  title="Groene button" 
  color="green"
  onPress={() => console.log('Groene button geklikt')}
/>

Button Disabled

<Button 
  title="Kan niet klikken" 
  disabled={true}
  onPress={() => console.log('Dit wordt niet uitgevoerd')}
/>

Belangrijke beperking van Button:

Je kunt Button NIET stylen met style prop! Alleen de color prop werkt. Voor custom styling moet je Pressable gebruiken.

Pressable Component

Pressable is een flexibele component voor interactieve elementen. Je kunt het volledig stylen naar wens!

Basis Pressable

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

export default function App() {
  return (
    <Pressable 
      style={styles.button}
      onPress={() => console.log('Pressable geklikt!')}
    >
      <Text style={styles.buttonText}>Klik mij</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#007AFF',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

Pressable met Hover Effect

Met style als functie krijg je toegang tot de pressed state:

<Pressable 
  style={({ pressed }) => [
    styles.button,
    pressed && styles.buttonPressed
  ]}
  onPress={() => console.log('Pressed!')}
>
  <Text style={styles.buttonText}>Druk mij</Text>
</Pressable>

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#007AFF',
    padding: 15,
    borderRadius: 8,
  },
  buttonPressed: {
    backgroundColor: '#0051D5',
    opacity: 0.8,
  },
  buttonText: {
    color: 'white',
    textAlign: 'center',
  },
});

Pressable Event Handlers

<Pressable
  onPress={() => console.log('Kort getikt')}
  onLongPress={() => console.log('Lang ingedrukt')}
  onPressIn={() => console.log('Druk begonnen')}
  onPressOut={() => console.log('Druk losgelaten')}
>
  <Text>Probeer verschillende presses!</Text>
</Pressable>

Voordelen van Pressable:

  • Volledig stylbaar met StyleSheet
  • Toegang tot pressed/hover states
  • Meer event handlers (onLongPress, onPressIn, etc.)
  • Kan elk element als child hebben

Button vs Pressable

Feature Button Pressable
Styling Alleen color prop Volledig stylbaar
Events Alleen onPress onPress, onLongPress, onPressIn, onPressOut
Children Alleen title (string) Elk component
Gebruik voor Snelle prototypes Productie apps

Vuistregel: Gebruik Button voor snelle tests, maar Pressable voor echte apps waar design belangrijk is.

TextInput & onChange

Met TextInput kunnen gebruikers tekst invoeren. Gebruik onChangeText om de waarde op te slaan.

Basis TextInput

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

export default function App() {
  const [text, setText] = useState('');

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        value={text}
        onChangeText={setText}
        placeholder="Typ hier..."
      />
      <Text>Je typte: {text}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ccc',
    padding: 10,
    borderRadius: 5,
    fontSize: 16,
  },
});

TextInput Props

<TextInput
  placeholder="Email adres"
  keyboardType="email-address"
  autoCapitalize="none"
  secureTextEntry={true}
  maxLength={50}
  multiline={true}
  onSubmitEditing={() => {
    console.log('Submitted!');
  }}
/>

Keyboard Types:

keyboardType="default"
keyboardType="number-pad"
keyboardType="email-address"
keyboardType="phone-pad"
keyboardType="url"

State Management met Events

Events worden vaak gecombineerd met useState om de UI te updaten op basis van gebruikersinteracties.

Counter Voorbeeld

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

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <View style={styles.container}>
      <Text style={styles.countText}>{count}</Text>
      
      <View style={styles.buttonRow}>
        <Pressable 
          style={styles.button}
          onPress={() => setCount(count - 1)}
        >
          <Text style={styles.buttonText}>-</Text>
        </Pressable>

        <Pressable 
          style={styles.button}
          onPress={() => setCount(0)}
        >
          <Text style={styles.buttonText}>Reset</Text>
        </Pressable>

        <Pressable 
          style={styles.button}
          onPress={() => setCount(count + 1)}
        >
          <Text style={styles.buttonText}>+</Text>
        </Pressable>
      </View>
    </View>
  );
}

Login Form Voorbeeld

import { useState } from 'react';
import { View, TextInput, Pressable, Text, Alert, StyleSheet } from 'react-native';

export default function LoginForm() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    if (!email || !password) {
      Alert.alert('Fout', 'Vul alle velden in');
      return;
    }
    console.log('Login met:', email, password);
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
        keyboardType="email-address"
        autoCapitalize="none"
      />

      <TextInput
        style={styles.input}
        placeholder="Wachtwoord"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />

      <Pressable 
        style={styles.loginButton}
        onPress={handleLogin}
      >
        <Text style={styles.buttonText}>Login</Text>
      </Pressable>
    </View>
  );
}

Event Types

Touch Events

Event Wanneer
onPress Kort tikken en loslaten
onLongPress Lang ingedrukt houden
onPressIn Zodra gebruiker begint te drukken
onPressOut Zodra gebruiker loslaat

Input Events

Event Wanneer
onChangeText Elke keer als tekst verandert
onSubmitEditing Enter/Return toets ingedrukt
onFocus Input krijgt focus
onBlur Input verliest focus

Alert Dialogs

Voor notificaties en confirmaties gebruik je de Alert API:

import { Alert } from 'react-native';

// Simpele alert
Alert.alert('Titel', 'Bericht');

// Alert met buttons
Alert.alert(
  'Weet je het zeker?',
  'Deze actie kan niet ongedaan worden',
  [
    { text: 'Annuleer', style: 'cancel' },
    { text: 'OK', onPress: () => console.log('OK') }
  ]
);

Praktijkvoorbeelden

Todo App

import { useState } from 'react';
import { View, TextInput, Pressable, Text, FlatList, StyleSheet } from 'react-native';

export default function TodoApp() {
  const [text, setText] = useState('');
  const [todos, setTodos] = useState([]);

  const addTodo = () => {
    if (text.trim()) {
      setTodos([...todos, { id: Date.now(), text }]);
      setText('');
    }
  };

  const deleteTodo = (id) => {
    setTodos(todos.filter(todo => todo.id !== id));
  };

  return (
    <View style={styles.container}>
      <View style={styles.inputRow}>
        <TextInput
          style={styles.input}
          value={text}
          onChangeText={setText}
          placeholder="Nieuwe todo..."
          onSubmitEditing={addTodo}
        />
        <Pressable style={styles.addButton} onPress={addTodo}>
          <Text style={styles.buttonText}>+</Text>
        </Pressable>
      </View>

      <FlatList
        data={todos}
        keyExtractor={item => item.id.toString()}
        renderItem={({ item }) => (
          <View style={styles.todoItem}>
            <Text style={styles.todoText}>{item.text}</Text>
            <Pressable onPress={() => deleteTodo(item.id)}>
              <Text style={styles.deleteText}>X</Text>
            </Pressable>
          </View>
        )}
      />
    </View>
  );
}

Like Button

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

export default function LikeButton() {
  const [liked, setLiked] = useState(false);
  const [likes, setLikes] = useState(42);

  const toggleLike = () => {
    setLiked(!liked);
    setLikes(liked ? likes - 1 : likes + 1);
  };

  return (
    <Pressable 
      style={[styles.button, liked && styles.liked]}
      onPress={toggleLike}
    >
      <Text style={styles.emoji}>{liked ? '❤️' : '🤍'}</Text>
      <Text style={styles.text}>{likes} likes</Text>
    </Pressable>
  );
}

Samenvatting

Pressable

Gebruik dit voor productie apps

onPress

Belangrijkste touch event

TextInput

Gebruik onChangeText met useState

Alert

Native dialogs voor notificaties

Je hebt nu geleerd:

  • Verschil tussen Button en Pressable
  • Event handlers zoals onPress, onChangeText
  • TextInput gebruiken voor formulieren
  • State management met useState en events
  • Praktijkvoorbeelden zoals counter, login en todo app