To modify the text displayed on a button, you must establish styling for the <Text>
element.
<Text style={{ color: /* insert state value here */ }}>Click Here</Text>
Illustration
The code snippet below is a variation of the Function Component illustration presented in the official documentation.
Reference: React Native / Docs / TouchableOpacity
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingHorizontal: 10
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10,
border: "thin solid grey"
}
});
const App = () => {
const [active, setActive] = useState(false);
const onPress = () => setActive(!active);
const buttonTextStyle = {
color: active ? 'green' : 'red'
};
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={onPress}
>
<Text style={buttonTextStyle}>Click Here</Text>
</TouchableOpacity>
</View>
);
};
export default App;
If you desire each button to function independently, you will have to introduce a new component.
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingHorizontal: 10,
gap: 10
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10,
border: "thin solid grey"
}
});
const StatefulButton = (props) => {
const { color, activeColor } = props;
const [active, setActive] = useState(false);
const onPress = () => setActive(!active);
const buttonTextStyle = {
color: active ? activeColor : color,
fontStyle: active ? 'unset' : 'italic',
fontWeight: active ? 'bold' : 'normal'
};
return (
<TouchableOpacity style={styles.button} onPress={onPress}>
<Text style={buttonTextStyle}>Click Here</Text>
</TouchableOpacity>
);
};
const App = () => {
return (
<View style={styles.container}>
<StatefulButton color="red" activeColor="green" />
<StatefulButton color="magenta" activeColor="cyan" />
</View>
);
};
export default App;