React Native Conditional Rendering

I will show you how I do conditional rendering in React Native.

react native conditional rendering

Create a new react native project if you don’t have one already. If so, you can use that because this example doesn’t require extra dependencies or settings.

react-native init conditional

Let’s create a common view in Android applications, the drawer toolbar UI pattern. We will DrawerLayoutAndroid and ToolbarAndroid for this, both from ‘react-native’ library.

Note: I did not bother creating an icon in the toolbar that when click it opens the drawer. If you want to test it just swipe right on the screen.

import React, {Component} from 'react';
import {DrawerLayoutAndroid, ToolbarAndroid, StatusBar, StyleSheet, Text, View} from 'react-native';

export default class App extends Component {
  render() {
    var drawer = (
      <View style={styles.drawer}>

      </View>
    );

    return (
      <DrawerLayoutAndroid renderNavigationView={() => drawer} drawerWidth={250}>
        <StatusBar backgroundColor="#c62726" barStyle="light-content"/>
        <ToolbarAndroid style={styles.toolbar} title="Conditional rendering" titleColor="white"/>
        <Text>Your info here...</Text>
      </DrawerLayoutAndroid>
    );
  }
}

const styles = StyleSheet.create({
  statusBar: {
    backgroundColor: '#015e9c'
  },
  toolbar: {
    backgroundColor: '#db4b3f',
    height: 56
  }
});

If all went good you should see this.

react native conditional rendering

That’s the screen when the user is logged in. But when he is not I want to display a button that redirects to the login view. I simply added a new view and a button. The view is not necessary but I added it in order to style the button, to have it in the center of the screen.

import React, {Component} from 'react';
import {DrawerLayoutAndroid, ToolbarAndroid, StatusBar, StyleSheet, Text, View, Button} from 'react-native';

export default class App extends Component {

  render() {
    var drawer = (
      <View style={styles.drawer}>

      </View>
    );

    return (
      <DrawerLayoutAndroid renderNavigationView={() => drawer} drawerWidth={250}>
        <StatusBar backgroundColor="#c62726" barStyle="light-content"/>
        <ToolbarAndroid style={styles.toolbar} title="Conditional rendering" titleColor="white"/>
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Button title="Click here to log in"/>
        </View>
      </DrawerLayoutAndroid>
    );
  }
}

const styles = StyleSheet.create({
  statusBar: {
    backgroundColor: '#015e9c'
  },
  toolbar: {
    backgroundColor: '#db4b3f',
    height: 56
  }
});

You should get this.

react native conditional rendering

But how to achieve conditional rendering in React Native? I want by using a condition to display either the text or the button. One solution might be this:

Create a state object and add a property called loggedIn.

constructor() {
    super();
    this.state = {
      loggedIn: false
    };
}

We cumbersomely modified our logic to use this.state.loggedIn flag and display either the text either the button.

Since we cannot use if else or other statements inside return () we had to duplicate the drawer, statusbar and toolbar code. We have one variant where it includes the text and one variant which includes the button.

import React, {Component} from 'react';
import {DrawerLayoutAndroid, ToolbarAndroid, StatusBar, StyleSheet, Text, View, Button} from 'react-native';

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      loggedIn: false
    };
  }

  render() {
    var drawer = (
      <View style={styles.drawer}>

      </View>
    );

    if (this.state.loggedIn) {
      return (
        <DrawerLayoutAndroid renderNavigationView={() => drawer} drawerWidth={250}>
          <StatusBar backgroundColor="#c62726" barStyle="light-content"/>
          <ToolbarAndroid style={styles.toolbar} title="Conditional rendering" titleColor="white"/>
          <Text>Your info here...</Text>
        </DrawerLayoutAndroid>
      );
    } else {
      return (
        <DrawerLayoutAndroid renderNavigationView={() => drawer} drawerWidth={250}>
          <StatusBar backgroundColor="#c62726" barStyle="light-content"/>
          <ToolbarAndroid style={styles.toolbar} title="Conditional rendering" titleColor="white"/>
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Button title="Click here to log in" onPress={() => this.setState({loggedIn: true})}/>
          </View>
        </DrawerLayoutAndroid>
      );
    }
  }
}

const styles = StyleSheet.create({
  statusBar: {
    backgroundColor: '#015e9c'
  },
  toolbar: {
    backgroundColor: '#db4b3f',
    height: 56
  }
});

But still, there must be a way to refactor this. The drawer, toolbar and statusbar remain the same regardless of the stuff displayed inside. We need to dynamically insert the text or the button inside the DrawerLayoutAndroid.

Conditional rendering in React Native

A better way of achieving conditional rendering in React Native is to store the markup (or component) inside a variable.

import React, {Component} from 'react';
import {DrawerLayoutAndroid, ToolbarAndroid, StatusBar, StyleSheet, Text, View, Button} from 'react-native';

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      loggedIn: false
    };
  }

  render() {
    var message;
    var drawer = (
      <View style={styles.drawer}>

      </View>
    );

    if (this.state.loggedIn) {
      message = <Text>Your info here...</Text>;
    } else {
      message = <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                  <Button title="Click here to log in" onPress={() => this.setState({loggedIn: true})}/>
                </View>;
    }
    return (
      <DrawerLayoutAndroid renderNavigationView={() => drawer} drawerWidth={250}>
        <StatusBar backgroundColor="#c62726" barStyle="light-content"/>
        <ToolbarAndroid style={styles.toolbar} title="Conditional rendering" titleColor="white"/>
        {message}
      </DrawerLayoutAndroid>
    );
  }
}

const styles = StyleSheet.create({
  statusBar: {
    backgroundColor: '#015e9c'
  },
  toolbar: {
    backgroundColor: '#db4b3f',
    height: 56
  }
});

We use a simple variable called message. Based on the loggedIn value it will either hold the <Text/> or the <Button/> component.

Then, inside DrawerLayoutAndroid we simply display the content of the {message} variable, regardless what it is.

I also added an onPress action on the button that changes the value from false to true so that you can see it works dynamically.

FacebookTwitterLinkedin