Home > Back-end >  How to make a React Native TextInput change Opacity just like TouchableOpacity?
How to make a React Native TextInput change Opacity just like TouchableOpacity?

Time:11-23

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?

CodePudding user response:

If you just want to set opacity, make your styles change using the onPressIn and onPressOut props:

const [pressed, setPressed] = useState(false);

// in render

  <TextInput
    onPressIn={() => setPressed(true)}
    onPressOut={() => setPressed(false)}
    style={pressed ? styles.textInputPressed : styles.textInput}
    // ...
  />

If you need the changes to animate, you can do that with the built-in RN Animated component or react-native-reanimated, using the same props to trigger the animations.

CodePudding user response:

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 for the show animation for the view
const clearTxtInput = () => {
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) 
//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 }) => {
     clearTxtInput(); // Callback after finish
  });
};
/*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>
  • Related