Search code examples
react-nativereact-native-reanimatedreact-native-stylesheet

How to make a React Native TextInput change Opacity just like TouchableOpacity?


My code looks something like this currently:

<View>
    <TextInput placeholder='PlaceholderText'>
    </TextInput>
</View>

I want to make a TextInput component that has an opacity animation on click (exactly like TouchableOpacity changes opacity on click).

I tried wrapping the TextInput inside TouchableOpacity, but it doesn't work since the touchable component surrounds text input. Is there a standard React Native or StyleSheet way of doing this or would I have to manually create an animation to mimic that effect?


Solution

  • Simply wrap your TextInput in a View element and animate the View's opacity color from the onFocs event of the TextInput. TextInput doesn't have the opacity attribute, therefore the additional view is required for your goal.

    Following code may give you an idea how to solve it. Have to admit, that I haven't tested the code, it may contain some error, so use it carefully.

        // First create an animated value to use for the view's opacity.
        const textInputAnimOpacity = useRef(new Animated.Value(1.0)).current;
        // create a method to set the opacity back to 1.0
        const showTxtInput = () => {
        Animated.timing(textInputAnimOpacity, {
          toValue: 1.0, // value to reach
          duration: 250 // time in ms 
          }).start();
        };
        
        // this animated method differs from the first one by (obviously the value 0.7) 
        //and the callback part that goes into the start()-method
        const blurTxtInput = () => {
        Animated.timing(textInputAnimOpacity, {
          toValue: 0.7, // value to reach
          duration: 250 // time in ms
          }).start(({ finished }) => {
             showTxtInput(); // Callback after finish, setting opacity back to 1.0
          });
        };
        /*Set the opacity to the value, we want to animate*/
        <View style={{opacity:textInputAnimOpacity}}>
            /* call blurTxtInput to set the value to 0.7 and again to 1.0 once it reaches 0.7*/
            <TextInput onPressIn={blurTxtInput} placeholder='PlaceholderText'>
            </TextInput>
        </View>