How to Conditionally Hide and Show a Component in React Native

Last Updated on December 10, 2020.

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

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

Go through the code snippet thoroughly to get firm understanding.

Class based component

import React, {Component} from 'react';

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

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      isVisible: true,
    };
  }

  toggleFunction = () => {
    this.setState((state) => ({
      isVisible: !state.isVisible,
    }));
  };

  render() {
    return (
      <View style={styles.container}>
        {this.state.isVisible ? (
          <Text style={styles.text}>Hello World!</Text>
        ) : null}

        <Button title="Toggle Visibility" onPress={this.toggleFunction} />
      </View>
    );
  }
}

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

Function based component

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.

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

Leave a Reply

%d bloggers like this: