React Native - TouchableOpacity



In this chapter we will show you button example using TouchableOpacity component.

Step1 - Create File

First we need to create src/components/home/TouchableOpacity.js file.

Step 2 - Logic

This is just a simple container component with no additional functionality.

src/components/home/HomeContainer.js

Example

import React, { Component } from 'react'
import TouchableOpacityExample from './TouchableOpacityExample'

export default class HomeContainer extends Component {

   constructor() {
      super();
   }
   render() {
      return (
         <TouchableOpacityExample buttonPressed = {this.buttonPressed}/>
      );
   }
}

Step 3 - Presentation

Presentational component is a simple button with some styling.

src/components/home/TouchableOpacityExample.js

Example

import React, { Component } from 'react'
import {
   View,
   TouchableOpacity,
   Text,
   StyleSheet
} from 'react-native'

export default TouchableOpacityExample = (props) => {
   return (
      <View style = {styles.container}>
         <TouchableOpacity>
            <Text style = {styles.button}>
               Button
            </Text>
         </TouchableOpacity>
      </View>
   )
}

const styles = StyleSheet.create ({
   container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
   },
   button: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black'
   }
})

When we press the button, opacity will change.

Output

TouchableOpacity
Advertisements