React Native Conditional Rendering

Shiv Yadav Oct 12, 2023
React Native Conditional Rendering

This article will help you to understand conditional rendering in React Native.

React Native Conditional Rendering

Conditional rendering in React Native is similar to conditional rendering in React. However, keep in mind that with React Native, we can only render strings within the Text component.

Code Example:

import React, {Component} from 'react';
import {Text, View} from 'react-native';

const Hello = (props) => (props.name ? <Text>Hello, {props.name}</Text> : null);

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
      age: 23,
      fruits: ["apple", "orange"],
    };
  }

  componentDidMount() {
    this.timer = setInterval(() => {
      this.setState({ date: new Date() });
    }, 1000);

    this.setState((state) => ({ age: state.age + 5 }));
    this.setState((state) => ({ age: state.age + 5 }));
    this.setState(
      (state) => ({ age: state.age + 5 }),
      () => {
        console.log("AGE: ", this.state.age);
      }
    );
    this.setState({ fruits: [...this.state.fruits, "banana"] });
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  render() {
    const { age, fruits } = this.state;
    return (
      <View>
        <Hello name="shiv" />
        <Hello name='jenn' />
        <Text>{this.state.date.toString()}</Text>
        {age < 75 ? (
          <Text>You are young: {age}</Text>
        ) : (
          <Text>You are not young: {age}</Text>
        )}

        {fruits.length > 0 && <Text>Your Fruits</Text>
}
{fruits.length > 0 ?
 (fruits.map(
     (fruit) => <Text key = {fruit}>{fruit} <
         /Text>)
        ) : (
          <Text>There are no fruits</Text >)} <
     /View>
    );
  }
}

export default App;

Output:

React Native Conditional Rendering

We declared a component Hello that takes state property as date, age, and fruits. The component is then rendered in the view component.

In the view component, we have given the value assigned to their property like the following.

<Hello name="shiv" />
<Hello name="jenn" />
<Text>{this.state.date.toString()}</Text>

After rendering the component, the componentDidMount will helps in executing the react code. The componentDidMount is executed only after rendering the component.

componentDidMount() {
  this.timer = setInterval(() => {
    this.setState({date: new Date()});
  }, 1000);

  this.setState((state) => ({age: state.age + 5}));
  this.setState((state) => ({age: state.age + 5}));
  this.setState((state) => ({age: state.age + 5}), () => {
    console.log('AGE: ', this.state.age);
  });
  this.setState({fruits: [...this.state.fruits, 'banana']});
}

You can see the setInterval is used here. The reason for using it is to set time intervals between components.

If an empty Hello component is assigned, it executes the following code, which results in a null value that means it will not print anything.

const Hello = (props) => (props.name ? <Text>Hello, {props.name}</Text> : null);

Now set an empty Hello component, and see what happens.

<View>
  <Hello name="shiv" />
  <Hello name="jenn" />
  <Hello />
  <Text>{this.state.date.toString()}</Text>
  {age < 75 ? (
    <Text>You are young: {age}</Text>
  ) : (
    <Text>You are not young: {age}</Text>
  )}

  {fruits.length > 0 && <Text>Your Fruits</Text>}
  {fruits.length > 0 ? (
    fruits.map((fruit) => <Text key={fruit}>{fruit}</Text>)
  ) : (
    <Text>There are no fruits</Text>
  )}
</View>

Output:

set an empty Hello component

In the output, you can see the age property. In the main code, we have set age = 23.

While rendering and executing the code, we increased the age by 15 and checked the ? or if-else conditions. After execution, the age becomes 38 and falls if the condition prints you are young: 38.

Suppose we change the age to age = 80.

this.state = {
  date: new Date(),
  age: 80,
  fruits: ['apple', 'orange'],
};

Output:

change age property

The output says, you are not young: 95. This happens because the code renders the else condition of age.

Let’s talk about the fruits state.

{
  fruits.length > 0 && <Text>Your Fruits</Text>;
}
{
  fruits.length > 0 ? (
    fruits.map((fruit) => <Text key={fruit}>{fruit}</Text>)
  ) : (
    <Text>There are no fruits</Text>
  );
}

See the name of fruits under Your Fruits because there is an if-else condition that tells if the number of fruits is more than 0, then it prints your fruits and the name of fruits available.

You can change the name of fruits if you want different fruits, or you can even change the component name if you like. When we remove the fruits and comment on the executable code for counting the number of fruits, it goes into another condition, giving an output there are no fruits.

this.state = {
  date: new Date(),
  age: 80,
  fruits: [],
};
// this.setState({ fruits: [...this.state.fruits, "banana"] });

Output:

rendered else condition of fruits

This way, we can use several props and component styles to render condition statements or values.

Author: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn

Related Article - React Native