Developer
Developer

Reputation: 141

change touchableopacity backgroundColor on button press react native

i want to change dynamically generated TouchableOpacity BackgroundColor OnPress in react native.

Upvotes: 6

Views: 12092

Answers (2)

William Ku
William Ku

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

Guillaume Piedigrossi
Guillaume Piedigrossi

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

Related Questions