Categories
JavaScript Answers React Native Answers

How to add if-else statement inside JSX with React Native?

Spread the love

Sometimes, want to add if-else statement inside JSX with React Native.

In this article, we’ll look at how to add if-else statement inside JSX with React Native.

How to add if-else statement inside JSX with React Native?

To add if-else statement inside JSX with React Native, we can put them in a function.

For instance, we write:

import * as React from 'react';
import { View, Text, Button } from 'react-native';
import { Card } from 'react-native-paper';

const App = () => {
  const [head, setHead] = React.useState(true);

  const showValue = () => {
    if (head) {
      return <Text>head</Text>;
    } else {
      return <Text>tail</Text>;
    }
  };

  return (
    <View>
      <Button title="flip" onPress={() => setHead((h) => !h)} />
      {showValue()}
    </View>
  );
};
export default App;

to create the showValue function that checks the value of the head state to render the text we want.

Then we add a Button to toggle the head value on press.

Finally, we call showValue to render the Text component returned in the function.

Conclusion

To add if-else statement inside JSX with React Native, we can put them in a function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *