How to use Pressable Component in React Native

The Pressable is a new core component introduced in React Native version 0.63. It is basically a wrapper that detects touch interactions. It is a well-defined component and can be used instead of touchable components such as TouchableOpacity, Button, etc.

The Pressable component is very easy to implement as given below.

<Pressable onPress={onPressFunction}>
  <Text>Press Me</Text>
</Pressable>

The Pressable component has so many useful props such as onPress, onLongPress, onPressIn, onPressOut, etc. You can get all details of the component from the official docs.

The following is the complete example of a Pressable component in react native.

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

const App = () => {
  return (
    <View style={styles.container}>
      <Pressable
        style={({pressed}) => [
          {
            backgroundColor: pressed ? 'red' : 'blue',
          },
          styles.button,
        ]}
        onPress={() => Alert.alert('Button Pressed!')}>
        <Text style={styles.buttonText}>Button</Text>
      </Pressable>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    borderRadius: 8,
    padding: 6,
    height: 50,
    width: '70%',
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 5,
  },
  buttonText: {
    fontSize: 16,
    color: 'white',
  },
});

In this example, the Pressable component acts as a button. It has a blue color background but it changes to red at the time of pressing. It turns blue again when the press is stopped. The onPress function shows an alert when the button is pressed.

Following is the output of the react native Pressable component example.

react native pressable example

I hope this react native tutorial will help you.

Similar Posts