Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change button style on press in React Native

I'd like the style of a button in my app to change when it is being pressed. What is the best way to do this?

like image 925
domi91c Avatar asked Jan 06 '16 04:01

domi91c


People also ask

How do I change the button style on a press in React Native?

To change button style on press in React Native, we can wrap our button with the TouchableHighlight component. 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.

How do you change the component on a click in react?

We have to set initial state value inside constructor function and set click event handler of the element upon which click, results in changing state. Then pass the function to the click handler and change the state of the component inside the function using setState.


1 Answers

Use TouchableHighlight.

Here an example:

enter image description here

import React from 'react'; import { TouchableHighlight, View, Text, StyleSheet } from 'react-native';  export default function Button() {    var [ isPress, setIsPress ] = React.useState(false);    var touchProps = {     activeOpacity: 1,     underlayColor: 'blue',                               // <-- "backgroundColor" will be always overwritten by "underlayColor"     style: isPress ? styles.btnPress : styles.btnNormal, // <-- but you can still apply other style changes     onHideUnderlay: () => setIsPress(false),     onShowUnderlay: () => setIsPress(true),     onPress: () => console.log('HELLO'),                 // <-- "onPress" is apparently required   };    return (     <View style={styles.container}>       <TouchableHighlight {...touchProps}>         <Text>Click here</Text>       </TouchableHighlight>     </View>   ); }  var 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,   } }); 
like image 172
Besart Hoxhaj Avatar answered Sep 28 '22 03:09

Besart Hoxhaj