react native-tutorial

React Native Touchables

The ability to capture the tapping functionality is provided by touchable components. If basic buttons don’t seem appropriate for your app, you can create the touchables component instead. You construct your own button using these parts. By tapping on these elements, the feedback can be seen.

Since the touchables components don’t come with any preset styling, you’ll need to create your own for them to look good in the app.

Syntax

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

Properties

  • TouchableHighlight: You can use it anywhere you would use a button or link on web. The view’s background will be darkened when the user presses down on the button.
  • TouchableOpacity: It can be used to provide feedback by reducing the opacity of the button, allowing the background to be seen through while the user is pressing down.
  • TouchableNativeFeedback: It is used in android to display ink surface reaction ripples that respond to the user’s touch.
  • TouchableWithoutFeedback: If you need to handle a tap gesture but you don’t want any feedback to be displayed, use TouchableWithoutFeedback.

Now let’s start with the implementation:

Step 1: Open your terminal and install expo-cli by the following command.

npm install -g expo-cli

Step 2: Now create a project by the following command.

expo init myapp

Step 3: Now go into your project folder i.e. myapp

cd myapp

Code

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}>Button</Text>
			</View>
		</TouchableHighlight>
		<TouchableOpacity onLongPress={() =>
			pressAlert("Long Pressed")} >
			<View style={styles.view}>
			<Text style={styles.text}>Long Press Button</Text>
			</View>
		</TouchableOpacity>
	</View>
);
}

const styles = StyleSheet.create({
container: {
	flex: 1,
	alignItems: 'center',
	justifyContent: 'center',
},
view : {
	width:250,
	height:50,
	backgroundColor : "blue",
	alignItems : "center",
	justifyContent : "center",
	borderColor : "black",
	borderWidth : 0.2
},
text : {
	fontSize : 20,
	color : "white"
},
Touch : {
	marginBottom : 30
}
});

Output

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *