Reputation: 141
i want to change dynamically generated TouchableOpacity BackgroundColor OnPress in react native.
Upvotes: 6
Views: 12092
Reputation: 798
The following code will set a random background colour on press.
How it works is to set the state colour on press and in its style, there is a backgroundColor object which uses the state colour for its value
import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
const colours = ['red', 'orange', 'yellow', 'blue', 'green', 'indigo', 'violet'];
const getColour = () => colours[Math.floor(Math.random() * colours.length)];
const Button = props => {
const [colour, setColour] = useState(getColour());
const handleClick = () => { setColour(getColour()); }
return (
<TouchableOpacity style={[styles.button, { backgroundColor: colour }]} onPress={handleClick}></TouchableOpacity>
);
}
const styles = StyleSheet.create({
button: {
borderColor: 'black',
borderWidth: 1,
width: 50,
height: 50,
}
});
export default Button;
Upvotes: 1
Reputation: 200
TouchableOpacity modifies the opacity (as its name says it). If you want to change the backgroundcolor on a touch, use TouchableHighlight instead
Upvotes: 9