Categories
JavaScript Answers React Native Answers

How to change button style on press in React Native?

Spread the love

Sometimes, we want to change button style on press in React Native.

In this article, we’ll look at how to change button style on press in React Native.

How to change button style on press in React Native?

To change button style on press in React Native, we can wrap our button with the TouchableHighlight component.

For instance, we write:

import * as React from 'react';
import { View, StyleSheet, Text, TouchableHighlight } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  btnNormal: {
    borderColor: 'blue',
    borderWidth: 1,
    borderRadius: 10,
    height: 30,
    width: 100,
  },
  btnPress: {
    borderColor: 'blue',
    borderWidth: 1,
    height: 30,
    width: 100,
  },
  btn: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    display: 'flex'
  }
});
export default function App() {
  const [isPress, setIsPress] = React.useState(false);

  const touchProps = {
    activeOpacity: 1,
    underlayColor: 'blue',
    style: isPress ? styles.btnPress : styles.btnNormal,
    onHideUnderlay: () => setIsPress(false),
    onShowUnderlay: () => setIsPress(true),
    onPress: () => console.log('hello'),
  };

  return (
    <View style={styles.container}>
      <TouchableHighlight {...touchProps}>
        <Text style={styles.btn}>Click here</Text>
      </TouchableHighlight>
    </View>
  );
}

to define the touchProps object that we use to set the props of TouchableHighlight.

We set onHideUnderlay to a function that runs when the underlay is hidden.

We set onShowUnderlay to a function that runs when the underlay is shown.

Both functions change the isPress state.

And we apply different styles for the TouchableHighlight according to the value of isPress.

Conclusion

To change button style on press in React Native, we can wrap our button with the TouchableHighlight component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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