Skip to content Skip to sidebar Skip to footer

Dynamic Opacity Not Changing When Component Rerenders In React Native

I'm starting to learn React Native, and for my project I created a simple Button component to reuse in my project. I set the opacity value dynamically according to the variable 'di

Solution 1:

not sure if it's a bug on the TouchableOpacity component, but the opacity won't update on a re-render until the component is clicked

to fix your problem just wrap the content of the touchable in a View and apply the opacity to the view instead of the touchable

exportdefaultfunctionButton({text, onPress, style, disabled, textStyle}) {
    const opacity = disabled === true ? 0.5 : 1// console.log('opacity', opacity)return (
        <TouchableOpacityonPress={onPress}disabled={disabled}style={[defaultStyles.button,style]}><Viewstyle={{opacity}}><Textstyle={[defaultStyles.text,textStyle]}>{text}</Text></View></TouchableOpacity>
    )

}

Solution 2:

For me it worked when I also changed the disabled prop together with the opacity.

I guess the issue is that the opacity in TouchableOpacity is an Animated.Value that overrides the value in the style prop and doesn't change, when the style prop changes...

Solution 3:

In my opinion correct solution is to use setOpacityTo method.

In your render:

render() {
  const opacityValue = this.props.disabled ? 0.5 : 1;
  return (
    <TouchableOpacitystyle={{opacity:opacityValue }} ref={(btn) => { this.btn = btn; }} onPress={this.onPress}>
      <Text>{this.props.text}</Text></TouchableOpacity>
  );
}

And next you can use setOpacityTo method in componentDidUpdate on disabled props change:

componentDidUpdate(prevProps) {
    const { disabled } = this.props;
    if (disabled !== prevProps.disabled) {
      const opacityValue = disabled ? 0.5 : 1;
      this.btn.setOpacityTo(opacityValue);
    }
  }

Solution 4:

If you are using React Native version 0.63 onwards then Pressable is more elegant solution to go with and its Opacity change works as expected.

<Pressablestyle={{opacity:item.isSelected ? 0.5:1
    }}>
       //Your button content goes here
</Pressable>

Post a Comment for "Dynamic Opacity Not Changing When Component Rerenders In React Native"