react-native
  1. react-native-touchables

React-Native Touchables

Syntax

There are multiple types of touchables in React-Native, which all have slightly different syntax:

import { TouchableOpacity, TouchableHighlight, TouchableWithoutFeedback, Pressable } from 'react-native';

<TouchableOpacity onPress={() => console.log('Pressed')}>
  <Text>Press Me</Text>
</TouchableOpacity>

<TouchableHighlight onPress={() => console.log('Pressed')}>
  <Text>Press Me</Text>
</TouchableHighlight>

<TouchableWithoutFeedback onPress={() => console.log('Pressed')}>
  <Text>Press Me</Text>
</TouchableWithoutFeedback>

<Pressable onPress={() => console.log('Pressed')}>
  <Text>Press Me</Text>
</Pressable>

Example

import { TouchableOpacity, Text } from 'react-native';

function MyButton({ text }) {
  return (
    <TouchableOpacity onPress={() => console.log('Button pressed')}>
      <Text>{text}</Text>
    </TouchableOpacity>
  );
}

export default MyButton;

Output

When the TouchableOpacity is pressed, the console will output "Button pressed".

Explanation

React-Native provides multiple touchable components that can be used to handle user interactions. These touchable components provide a consistent way to handle touch events across different mobile devices.

The different touchable components have slightly different behavior and styles:

  • TouchableOpacity: Reduces the opacity of the component when pressed
  • TouchableHighlight: Highlights the component when pressed
  • TouchableWithoutFeedback: Does not provide any visual feedback when pressed
  • Pressable: A versatile component that can provide different types of feedback based on the presence of certain props

Use

React-Native touchables can be used in any mobile application to handle user interactions, such as button presses, taps, and swipes.

It is important to choose the correct touchable component for the desired behavior - for example, TouchableWithoutFeedback may be more appropriate for a background element that doesn't require visual feedback, while TouchableOpacity is a good choice for buttons.

Important Points

  • Touchables should usually wrap other components, such as text or images.
  • Touchables can be customized with various props, such as activeOpacity for TouchableOpacity to control the opacity when pressed.
  • Touchable components can be nested inside other touchables, but care should be taken to prevent accidental triggering of touch events.

Summary

React-Native touchables provide a consistent and versatile way to handle touch events in mobile applications. By choosing the appropriate touchable component and customizing its props, we can create intuitive and responsive user interfaces.

Published on: