React Native - TouchableHighlight



We already mentioned touchable components in one of our previous chapters. This chapter will show you how to use TouchableHighlight component.

Step1 - Create File

We already done this in our previous chapters. We will create src/components/home/TouchableHighlight.js file.

Step 2 - Logic

This is container component. We are passing buttonPressed function as a prop.

src/components/home/HomeContainer.js

Example

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

export default class HomeContainer extends Component {

   constructor() {
      super();
   }
   buttonPressed = () => {
      console.log('TouchableHighlight pressed...');
   }
   render() {
      return (
         <TouchableHighlightExample buttonPressed = {this.buttonPressed}/>
      );
   }
}

Step 3 - Presentation

This component is our button. underlayColor will be visible when button is pressed.

src/components/home/TouchableHighlightExample.js

Example

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

export default TouchableHighlightExample = (props) => {
   return (
      <View style = {styles.container}>
         <TouchableHighlight underlayColor = {'red'} onPress = {props.buttonPressed}>
            <Text style = {styles.button}>
               Button
            </Text>
         </TouchableHighlight>
      </View>
   )
}

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

You can press the button to see red color.

Output

TouchableHighlight
Advertisements