Categories
JavaScript Answers React Native Answers

How to show or hide components in React Native?

Spread the love

Sometimes, we want to show or hide components in React Native.

In this article, we’ll look at how to show or hide components in React Native.

How to show or hide components in React Native?

To show or hide components in React Native, we can write ternary expressions to display components according to a value.

For instance, write:

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

const MyComponent = () => {
  const [show, setShow] = React.useState(false);
  return (
    <View>
      <Button onPress={() => setShow((s) => !s)}>toggle</Button>
      {show ? <Text>show</Text> : <Text>hide</Text>}
    </View>
  );
};

export default MyComponent;

to display ‘show’ if show is true and ‘hide’ otherwise.

We control the value of show with the toggle button.

To change it, we set onPress to a function that calls setShow with a callback to toggle the show value.

Therefore, when we press the button, we see the text toggle between ‘show’ and ‘hide’.

Conclusion

To show or hide components in React Native, we can write ternary expressions to display components according to a value.

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 *