Create a Button in React Native Using TouchableOpacity

Kadi Kraman
InstructorKadi Kraman

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 3 years ago

Create a button in React Native using Text and TouchableOpacity, and customise the look and feel of your button using the style prop and activeOpacity.

Using TouchableOpacity is of the most commonly used ways of building buttons in React Native. It is much more versatile than the built in Button component: you can wrap anything (an Image, View, Text etc) in a TouchableOpacity, to make it into a button, and add any styles for both the button container as well as the children to customise them.

Kadi Kraman: [0:00] First, let's import text from React Native and give our button a name. I'm going to call it a Touchable Button. I'm also going to give it some styles to make it more visible. Let's do style="color:white" and font-size:24. Now you can see the button text is displayed on the screen.

[0:19] Next, let's import a TouchableOpacity from React Native. Let's wrap the whole text with this TouchableOpacity. You can see when I press this, the button text gets lighter. That's the opacity side of TouchableOpacity.

[0:34] We can change this using activeOpacity prompt, which takes in a value between and 1. If I was to pass in 1, you can see that nothing happens at all. If I was to pass in , you can see that the button disappears altogether. Usually, you would pass in something in between.

[0:51] Finally, let's handle the onPrecedent by triggering an alert. Let's do alert(Alert) and a Touchable Button pressed. When I press this, the alert is being triggered.

[1:04] Let's use the style prop to make this a little bit more like a button. I'm going to use a background-color of teal, a padding of 15, and a border-radius of 5. When I save this, this looks quite a bit like a button.

[1:21] Using a TouchableOpacity can be much more versatile than the built-in button component because you can turn anything into a button by wrapping it in a TouchableOpacity and then style whatever you pass inside. You can also configure the styles for a TouchableOpacity itself as well as the activeOpacity.