Search code examples
react-nativestylesheet

React native dynamic style without re render the whole component


Is this conditional styling below still works with react native?

style={[styles.base, this.state.active && styles.background]}

When the component is mounted, the active state is set to false.

The screen has a button to change the active state to true. Then, I would expect the background style to be displayed. But it is not the case unless the page reload.

Any thought ?

Thanks


Solution

  • It sounds like you'd be interested in using the Animated Module from react-native. By using the Animated module, you can have styles that change or animate. You could also use LayoutAnimation. You should read the Animation Documentation and LayoutAnimation documentation.

    You can start off by using LayoutAnimation and see if that does what you need. It's quick to set up!

    Here's an example:

    import React, { Component} from 'react';
    import { View, LayoutAnimation, UIManager, Platform } from 'react-native';
    
    class MyComponent extends Component {
        constructor(props) {
            super(props);
    
            if (Platform.OS === 'android') {
                UIManager.setLayoutAnimationEnabledExperimental(true);
            }
        componentWillUpdate() {
            LayoutAnimation.spring() // automatimagically animates style changes
        }
        render() {
            <View style={[styles.base, this.state.active && styles.background]}>
            </View>
        }
    }