Buttons and TouchableOpacity

I don’t know who came up with the name ‘TouchableOpacity’, but anyway…

When building a mobile application, mostly likely everything won’t be on a single page, either to prevent excessive scrolling or just to keep it organized. The use of buttons to help navigate is a pretty obvious option. React Native has two main ways of using buttons to navigate from one screen to another. Button and Touchable Opacity.

In a recent post, I spoke about basics of React Native, simple building blocks to help anyone already familiar with React get started with building mobile applications. The post covered View, Text, and StyleSheet; buttons should probably be covered as well. For example a very simple component would look like:

import React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
const basicComponent = () => {
return (
<View>
<Button>Press me!</Button>
</View>
)
}
const styles = StyleSheet.create({})export default basicComponent

Tada!

This will generate a button on your device/emulator and it will be styled as follows;

Buttons can be programmed to navigate to a different screen, cause a pop-up, really do what ever you want. When building the component use the onPress() method.

import React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
const basicComponent = () => {
return (
<View>
<Button onPress={() => console.log("Pressed!"}>Press me!</Button>
</View>
)
}
const styles = StyleSheet.create({})export default basicComponent

Another form of button is called TouchableOpacity, is does the same thing as a Button and is imported the exact same way:

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
const basicComponent = () => {
return (
<View>
<TouchableOpacity onPress={() => console.log("Pressed!"}>Press me!</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({})export default basicComponent

Styling wise, TouchableOpacity looks a little different, it won’t come with any default style like the example above, feel free to style as you like, but when pressed, whatever is wrapped in the tags will briefly fade in and out with some built in animation, pretty cool!

Programmer’s choice when it comes to which one you want to use. With styling, Buttons and TouchableOpacitys can lead to some amazing creations.

And that will put a button on it!

Software Engineer in NYC with expertise in Ruby on Rails, JavaScript, and React