Search code examples
react-nativebuttontouchableopacityonpress

React Native TouchableOpacity when I click, change color or Opacity


firstable, I'm korean. I'm not good at eng. so plz understand me about garmmar or word.

anyway,

now I use TouchableOpacity, and I want to change the brightness when I push the button like the photo.

enter image description here

(I dont need checkmark. just brigtness.)

I'm so glad If you upload the all of code, not part of it. because I'm begginer, I can't use part of code. sorry.

plz help me... I have been soooo many time in this problem.


Solution

  • From my understanding, you want to utilize an overlay on the image when clicked. So to do this we will do three things.

    1. Add TouchableOpacity as a Parent View
    2. Add Child Image
    3. Add Child Overlay View with 60% Opacity
    4. Create overlay Boolean useState()
    5. Add Toggle Function to update the overlay value

    Full Code for Functional Components

    import * as React from 'react';
    import { useState } from 'react';
    import { View, StyleSheet, TouchableOpacity, Image } from 'react-native';
    
    
    export default function App() {
      
      // Variables
    
      // overlay Boolean useState()
      const [overlay, setOverlay] = useState(false);
    
      // Functions 
      const toggleOverlay = () => {
        setOverlay(!overlay);
      }
    
      // Render
      return (
        <View style={styles.container}>
    
          {/*Parent TouchableOpacity */}
          <TouchableOpacity style={styles.parent} onPress={() => toggleOverlay()}>
    
            {/*Child Image */}
            <Image
              source={{ uri: 'https://picsum.photos/200/300' }}
              style={styles.childImage}
            />
    
            {/*Child Overlay w/ Conditional Rendering */}
            {overlay && <View style={styles.childOverlay} />}
    
          </TouchableOpacity>
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingTop: 20,
        backgroundColor: 'white',
        padding: 8,
      },
      parent: {
        width: 200,
        height: 150,
        backgroundColor: 'grey',
        borderRadius: 5,
      },
      childImage: {
        width: '100%',
        height: '100%',
        borderRadius: 5,
      },
      childOverlay: {
        width: '100%',
        height: '100%',
        borderRadius: 5,
        backgroundColor:'black',
        opacity:0.6,
        position:'absolute'
      }
    });