How to Add a Simple Toggle Function in React Native

Last Updated on December 11, 2020.

Toggle functions are used when we want to toggle certain components or items. For example, we use the toggle function in the Favorites section of the mobile app. The favorite icon toggles when the item is either added or removed.

So, here is a react native code snippet that toggles the text written in the Text Component. When the Touchable Opacity component pressed, the state changes, and then the text also changes.

import React, {useState} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';

const App = () => {
  const [toggle, setToggle] = useState(true);
  const toggleFunction = () => {
    setToggle(!toggle);
  };
  return (
    <View>
      <TouchableOpacity onPress={() => toggleFunction()}>
        <Text>{toggle ? 'Add to Favorites' : 'Remove from Favorites'}</Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

Following is the output of the example where the text toggles when the TouchableOpacity is pressed.

react native toggle function

This is the right way to write a simple toggle function in react native.

Leave a Reply

%d bloggers like this: