CodeBlanks Logo Icon CodeBlanks

Summary - Events

Combine onPress, onLongPress and form events to write a feedback form.

Summary - Events

This group covered tap and form events. onPress catches a quick tap, onLongPress a long hold. Handlers take an event parameter; you read position and data from nativeEvent.

onLayout reports layout changes; you read layout.width and layout.height. In forms, onChangeText fires on each keypress and onSubmitEditing on the submit key. Now you will combine these in two mini tasks.

Practice A feedback form

Write an App component. Define text with useState(''). Show <Text>Send</Text> inside a <TouchableOpacity>; its onPress should call {`() => console.log(text)`}. Above it, add a <TextInput> with value={'{text}'} and onChangeText={'{setText}'}. Export the App function.

Starter code

App.js
import { useState } from 'react';
import { TextInput, TouchableOpacity, Text } from 'react-native';

// write the feedback form here

Sample solution

App.js
function App() {
  const [text, setText] = useState('');
  return (
    <>
      <TextInput value={text} onChangeText={setText} />
      <TouchableOpacity onPress={() => console.log(text)}>
        <Text>Send</Text>
      </TouchableOpacity>
    </>
  );
}
export default App;

Practice A card that measures layout

Write an App component. Define height with useState(0). Give the <View> an onLayout handler that calls setHeight with event.nativeEvent.layout.height. Put <Text>{`{height}`}</Text> inside. Give style a height: 120. Export the App function.

Starter code

App.js
import { useState } from 'react';
import { View, Text } from 'react-native';

// write the layout-measuring card here

Sample solution

App.js
function App() {
  const [height, setHeight] = useState(0);
  return (
    <View
      onLayout={(event) => setHeight(event.nativeEvent.layout.height)}
      style={{ height: 120 }}>
      <Text>{height}</Text>
    </View>
  );
}
export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match all the event concepts

Term Meaning
onPress Quick tap
onLongPress Long hold
onLayout Layout change
onChangeText Text change

2 What catches form submission?

  • onChangeText Correct answer
  • onLayout
  • onSubmitEditing
  • onLongPress

Explanation: onSubmitEditing listens for the keyboard submit key.

All lessons in Beginner