← Back to Chapters

Toggle Show / Hide in React Native

? Toggle Show / Hide in React Native

? Quick Overview

Toggle Show / Hide is a common UI pattern in React Native used to conditionally display components such as text, views, forms, or images using state management.

? Key Concepts

  • useState hook for state management.
  • Conditional rendering using the Logical AND operator (&&) or Ternary operator (? :).
  • Button or TouchableOpacity to trigger the toggle event.

? Syntax / Theory

React Native re-renders the component whenever the state changes. By toggling a boolean variable between true and false, we can control the existence of UI elements.

? View Code Example
// 1. Import useState
import React, { useState } from "react";
import { View, Text, Button } from "react-native";

const ToggleExample = () => {
  // 2. Define State (initially false/hidden)
  const [visible, setVisible] = useState(false);

  return (
    <View>
      // 3. Button toggles state on press
      <Button 
        title={visible ? "Hide Text" : "Show Text"} 
        onPress={() => setVisible(!visible)} 
      />

      // 4. Conditional Rendering
      {visible && <Text>Hello React Native!</Text>}
    </View>
  );
};

export default ToggleExample;

?️ Live Output / Explanation

When the button is pressed, the visible state flips. If true, the Text component is added to the screen. If false, it is removed entirely.

? Interactive Concept Simulator

Use the simulator below. Notice how the Button Text changes and the Content appears based on the value of the State Variable.

My App
// React State Monitor
const [visible, setVisible] = useState(false);

? Use Cases

  • Accordions: Expanding FAQs to show answers.
  • Security: Toggling password visibility (mask/unmask).
  • Forms: Showing extra fields based on a checkbox.
  • Loading: Showing a spinner while data loads.

✅ Tips & Best Practices

  • Use !visible to easily flip the current boolean value.
  • For complex conditions, wrap the toggle logic in a handler function.
  • Always initialize your state (e.g., useState(false)).

? Try It Yourself

  1. Change the code to hide the element initially (start with true).
  2. Replace the standard Button with a TouchableOpacity.
  3. Try toggling an Image component instead of Text.