How to use Pressable in React Native? Code Example

Total
0
Shares

<Pressable> is the core component to record different stages of press events. React Native recommends using this in place of TouchableHighlight, TouchableWithoutFeedback and TouchableOpacity.

Let’s see how pressable works –

1. User pressed the button normally

The events will occur in this series –

onPressIn (When pressed)
⬇️
onPressOut (When button released)
⬇️
onPress (after onPressOut)

2. User long pressed the button

The press events will occur in this series for long-press –

onPressIn (When pressed)
⬇️ After 500ms
onLongPress
⬇️
onPressOut (When button released)

There are two important options in pressable component –

  • HitRect – Suppose your component is small but you want users to give more room for tap then you can set a bigger area for tapping. This can be done using HitRect property. It is set by hitSlop prop.
  • PressRect – If a user drags her finger away from clickable element then clicks do not register. But we can give some room for that. We can set a bond up to which if a user drags finger when button is in pressed state and release the finger, then it will still count as click. It is set by pressRetentionOffset prop.

Important Properties

1. In style prop, you will get current state of component – pressed or not pressed. Like this –

<Pressable
  style={({pressed}) => [{backgroundColor: pressed ? '#FF0000' : '#DDDDDD'}]}
>

</Pressable>

2. You will also get the pressed state for child component. Like this –

<Pressable>
 
  {({ pressed }) => (
       <Text>
         {pressed ? "I am currently Pressed" : "Not Pressed"}
       </Text>
  )}

</Pressable>

Code Example

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

const PressableComponent = () => {
  
  return (
    <View style={styles.container}>
      <Text>Simple Pressable</Text>
      <Pressable
        onPress={() => {Alert.alert('Simple Button Pressed')}}
      >
        <View style={styles.button}>
          <Text>
            I am Simple Button
          </Text>
        </View>
      </Pressable>

      <Text>TouchableOpacity from Pressable</Text>
      <Pressable
        onPress={() => {Alert.alert('TouchableOpacity Button Pressed')}}
        style={({pressed}) => [{
          opacity: pressed ? 0.2 : 1
        }]}
      >
        <View style={styles.button}>
          <Text>
            TouchableOpacity Way
          </Text>
        </View>
      </Pressable>

      <Text>TouchableHighlight from Pressable</Text>
      <Pressable
        onPress={() => {Alert.alert('TouchableOpacity Button Pressed')}}
        style={({pressed}) => [styles.button, {
          opacity: pressed ? 0.6 : 1,
          backgroundColor: pressed ? '#FF0000' : '#DDDDDD'
        }]}
      >
        <View>
          <Text>
            TouchableHighlight Way
          </Text>
        </View>
      </Pressable>
      
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
  },
  button: {
    padding:10,
    margin: 10,
    backgroundColor: '#DDDDDD',
  }
  
});

export default PressableComponent;

Output –

Pressable in React native. Emulating TouchableHighlight and TouchableOpacity in Pressable.

From the image you can see that we have 3 phones of iOS and Android OS. All of them are showing 3 buttons.

In the first phone, we have pressed the 1st button but nothing is visually different. This is due to the default styling of pressable. It appears like TouchableWithoutFeedback button.

In the second phone, we are pressing 2nd button and it’s opacity is reduced while it’s in pressed state. This is due to the opacity style we used in code at line 23. This button has emulated the functionality of TouchableOpacity.

In the third phone, we are pressing 3rd button. The opacity is reduced and there is a red background color, just like we saw in TouchableHighlight article. This is because of the style in code from line 36 to 39.

This proves that Pressable component can create any kind of styling and we don’t need to use previous touchable components.

Live Demo

Open Live Demo

Conclusion

Pressable is the core api which is used to wrap components and add press events for them. It is future proof and better than other touchable components. You can create any kind of styles because it provides pressed flag in style prop as well as to the child component.


React Native Series

Alert

  1. Basic Alert
  2. Dismiss on Clicking Outside
  3. Input Fields in Alert Dialog – Prompt()
  4. Dark-Light Theme of Dialog

ActivityIndicator

  1. Basic Circular Loader
  2. Change size of Circular Loader
  3. Show/hide Circular Loader
  4. Change color of Circular Loader

Button

  1. Simple Button
  2. Change Button Color
  3. Disable Button Click
  4. Disable touch sound on Button click

FlatList

  1. Simple List
  2. Single Item Selection from List
  3. Multiple Item Selection from List
  4. Adding separator between list items
  5. Multiple columns List
  6. Showing Message in Empty List
  7. Add Footer to the List
  8. Add Header to the List
  9. Horizontal List
  10. Inverted List
  11. Pull to Refresh in List
  12. Infinite Loading List

SectionList

  1. Section List

ScrollView

  1. ScrollView
  2. Stick Single Item at Header
  3. Stick Multiple Items at Header
  4. Stick Item at Footer
  5. Hide Sticky Element on Scroll

Image

  1. Display Image from remote url
  2. Display local storage image
  3. Display Base64 Image
  4. Display Gif & Webp Images
  5. Adding Blur to Image
  6. Displaying loader for Image
  7. Resizemode for Images
  8. Setting Default Placeholder Image
  9. Background Image

Modal

  1. Basic Modal
  2. Slide from bottom Modal
  3. Fade In Modal
  4. Transparent Overlay Modal

RefreshControl

  1. RefreshControl
  2. Change Refresh Loader Color
  3. Change Refresh Loader Size
  4. Change Refresh Loader Background Color
  5. Title under Refresh Loader
  6. Change color of title under refresh loader

StatusBar

  1. Get StatusBar Size
  2. Change StatusBar Background Color
  3. Display StatusBar icons & text in While Color
  4. Display StatusBar icons & text in Dark Color
  5. Hiding StatusBar
  6. Translucent StatusBar

Switch

  1. Simple Switch
  2. Disable Switch
  3. Change Switch Colors

Text

  1. Adding Text
  2. Bold Text
  3. Italic Text
  4. Underline Text
  5. Selecting Text for copy-paste
  6. Changing Highlight Color of Text Selection
  7. Fit text in View box
  8. Clickable anchors in text
  9. Truncate Lengthy Text

TextInput

  1. Simple Input Field
  2. Auto Capitalize Text in Input Field
  3. Multiline Input Field
  4. Hide Cursor in Input Field
  5. Clear input Field using X
  6. Clear input Field when focused
  7. Change Cursor Color in Input Field
  8. Disable input field
  9. Icon at the left of Input Field
  10. Dark-Light Keyboard
  11. Avoid Overlapping of Keyboard
  12. Limiting Characters in Input Field
  13. Numeric Keyboard
  14. Email Id Keyboard
  15. Phone number Keyboard
  16. Url Keyboard
  17. Placeholder in input field
  18. Placeholder Color in Input Field
  19. Password Input Field
  20. Programmatically select text in Input Field
  21. Change Text Selection Color in Input Field
  22. Select Whole text in Input Field on Focus
  23. Write text from center in input field
  24. Changing underline color of input field

TouchableWithoutFeedback

  1. TouchableWithoutFeedback

TouchableHighlight

  1. TouchableHighlight

TouchableOpacity

  1. TouchableOpacity

Pressable

  1. Pressable
  2. Creating Ripple Effect

Appearance

  1. Dark-Light System Color Scheme

AppState

  1. AppState – Foreground/Background State of App

ToastAndroid

  1. Creating Android Toast Message

Dimensions

  1. Getting Screen & Window Dimensions

Keyboard

  1. Dismiss Keyboard Programmatically

👉 Learn Material Design using React Native Paper