How to Conditionally Hide and Show a Component in React Native

In some situations, you might need to show and hide components conditionally in React Native. Hiding as well as showing React Native components can be done using the state management and ternary operators.

In the example given below, I am setting a state named isVisible with the value true, which means the text component will be visible initially. When the button is pressed, we change the isVisible state to false. This will make the text invisible.

Go through the code snippet thoroughly to get a firm understanding.

import React, {useState} from 'react';

import {StyleSheet, Text, View, Button} from 'react-native';

const App = () => {
  const [isVisible, setIsVisible] = useState(true);

  const toggleFunction = () => {
    setIsVisible(!isVisible);
  };

  return (
    <View style={styles.container}>
      {isVisible ? <Text style={styles.text}>Hello World!</Text> : null}
      <Button title="Toggle Visibility" onPress={toggleFunction} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    flex: 1,
    margin: 10,
  },
  text: {
    fontSize: 20,
    color: 'red',
    textAlign: 'center',
  },
});

export default App;

Following is the output of this react native example.

react native hide and unhide components

This is how you hide and show components in react native.

Similar Posts

Leave a Reply