Kyle Banks

How to Conditionally Render a Component in React Native

Written by @kylewbanks on Oct 22, 2016.

In today’s post, I’d like to share with you how I conditionally render components in React Native.

Let’s say you want to show a Log In button for unauthenticated users, and a Log Out button for user’s who have authenticated. How would you go about doing this?

One way would be to hide the button that shouldn’t be visible, but without a comparative version of display: none on Web or Visibility.GONE on Android, there’s no really good built in way to do this. You could set the opacity to hide the view, but it would still take up the appropriate space, so this isn’t an ideal solution.

What I prefer to do is use a renderIf function. The function takes a boolean parameter and a component, and if the boolean is true it returns the component, and if not it returns null.

Take a look:

export default function renderIf(condition, content) {
    if (condition) {
        return content;
    } else {
        return null;
    }
}

Simple enough, right? Put this in a file called renderIf.js so you can import and use the function elsewhere.

So how do you use it? Let’s pretend our component has a isUserLoggedIn property on it’s state, and we want to toggle the display of a LogInButton and LogOutButton based on this property:

import renderIf from './renderIf';

class ConditionalView extends Component {
    render() {
        return (
            <View>
                {renderIf(this.state.isUserLoggedIn, 
                    <LogOutButton />
                )}
                
                {renderIf(!this.state.isUserLoggedIn,
                    <LogInButton />
                )}
            </View>
        )
    }
}

Now when isUserLoggedIn is true, the LogOutButton will be displayed, and when isUserLoggedIn is false, the LogInButton will be displayed.

Of course for more complicated renders, it would be advisable to break components out into their own classes that can perform logic internally, or to create a function such as renderAuthButton (for example), and call that from render and perform the logic inside the renderAuthButton function. However that being said, I still do find uses for renderIf style functions occasionally, so it’s a nice little tool to have available.

Let me know if this post was helpful on Twitter @kylewbanks or down below, and follow me to keep up with future posts!