Dynamic Opacity not changing when component rerenders in react native
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
export default function Button({text, onPress, style, disabled, textStyle}) { const opacity = disabled === true ? 0.5 : 1 // console.log('opacity', opacity) return ( <TouchableOpacity onPress={onPress} disabled={disabled} style={[defaultStyles.button, style]}> <View style={{opacity}}> <Text style={[defaultStyles.text, textStyle]}>{text}</Text> </View> </TouchableOpacity> )}
In my opinion correct solution is to use setOpacityTo method.
In your render
:
render() { const opacityValue = this.props.disabled ? 0.5 : 1; return ( <TouchableOpacity style={{ 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); } }
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.
<Pressable style={{ opacity: item.isSelected ? 0.5 : 1 }}> //Your button content goes here</Pressable>