Open In App

React Native Touchables Component

In this article, We are going to see how to create a Touchables in react-native. For this, we are going to use Touchable components. It is used to make any component touchable.

Syntax:



<TouchableHighlight onPress={}>
    // Inside Components        
</TouchableHighlight>

Components in Touchables:

Now let’s start with the implementation:



Project Structure: It will look like the following.

Example: Now let’s implement the Touchable. Here we created our view as touchable.

App.js




import React from 'react';
import { StyleSheet, View , TouchableHighlight , TouchableOpacity , Text , Alert } 
from 'react-native';
export default function App() {
  const pressAlert = (text) => {
    Alert.alert("You " + text +  " me");
  }
  return (
    <View style={styles.container}>
        <TouchableHighlight style={styles.Touch} 
            onPress={() => pressAlert("Pressed")} >
            <View style={styles.view}>
              <Text style={styles.text}>Press Me</Text>
            </View>
        </TouchableHighlight>
        <TouchableOpacity onLongPress={() => 
               pressAlert("Long Pressed")} >
            <View style={styles.view}>
              <Text style={styles.text}>Long Press Me</Text>
            </View>
        </TouchableOpacity>
    </View>
  );
}
  
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  view : {
    width:250,
    height:50,
    backgroundColor : "lightgreen",
    alignItems : "center",
    justifyContent : "center",
    borderColor : "black",
    borderWidth : 0.2
  },
  text : {
    fontSize : 20,
    color : "white"
  },
  Touch : {
    marginBottom : 30
  }
});

Start the server by using the following command.

npm run android

Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. 

Reference: https://reactnative.dev/docs/handling-touches


Article Tags :