javascriptreact-nativebuttonstyling

How I make a button change color when I press in React Native?


My button does not change color. Here s my code:

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const MyButton = () => {
  const [isPressed, setIsPressed] = React.useState(false);

  const handlePressIn = () => {
    setIsPressed(true);
  };

  const handlePressOut = () => {
    setIsPressed(false);
  };

  return (
    <TouchableOpacity
      onPressIn={handlePressIn}
      onPressOut={handlePressOut}
      style={[styles.button, isPressed && styles.buttonPressed]}
    >
      <Text style={styles.buttonText}>Press Me</Text>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    backgroundColor: 'blue',
    padding: 10,
    borderRadius: 5,
  },
  buttonPressed: {
    backgroundColor: 'red',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
  },
});

export default MyButton;

What am I doing wrong? Button does not change color.

I am trying to change the color when the button is pressed.
Expecting the button to turn red but it stays blue.


Solution

  • I think inherently, using TouchableOpacity will be tricky in solving this, so I wouldn't recommend using it for this case since it already has it's own behavior to handle the touch feedback. What you're looking for is like below but using react-native's Pressable component instead and it's just simple like so:

    <Pressable
      style={({pressed}) => [
        styles.button,
        {
          backgroundColor: pressed ? 'red' : 'blue',
        },
        styles.wrapperCustom,
      ]}
    >
      <Text style={styles.buttonText}>Press Me</Text>
    </Pressable>