DEV Community

Cover image for How to Handle Multiple Switches in React Native
Amit Kumar
Amit Kumar

Posted on

How to Handle Multiple Switches in React Native

Switch components are a great way to allow users to toggle settings on and off in a React Native application. In this guide, we'll walk through handling multiple switches efficiently using React Native's state management.

Introduction

Many applications require users to toggle multiple preferences, such as selecting interests or enabling certain features. React Native's Switch component provides a seamless way to implement this functionality. In this tutorial, we will build a feature that allows users to customize their interests by toggling multiple switches.


Setting Up the Component

We start by defining an array of objects containing details about each switch, including an icon, label, and isActive status.

const DATA = [
  {
    icon: 'https://cdn-icons-png.freepik.com/256/3689/3689556.png',
    id: 0,
    isActive: false,
    label: 'Shopping',
  },
  {
    icon: 'https://cdn-icons-png.freepik.com/256/826/826070.png',
    id: 1,
    isActive: true,
    label: 'Travel',
  },
  // Additional items...
];
Enter fullscreen mode Exit fullscreen mode

Implementing the MultiSliderComponent

We use the useState hook to manage the state of the switches. The toggleSwitch function updates the isActive state when a switch is toggled.

const [switches, setSwitches] = useState(DATA);
const [displayText, setDisplayText] = useState([]);

const toggleSwitch = id => {
  setSwitches(prevState =>
    prevState.map(item =>
      item.id === id ? { ...item, isActive: !item.isActive } : item
    )
  );
};
Enter fullscreen mode Exit fullscreen mode

We then map over the switches array to render each switch component dynamically:


{displayText.length && (
          <Text
            style={styles.titleStyle}>{`You have selected: ${displayText}`}</Text>
        )}

{switches.map((item, index) => (
  <View key={index} style={styles.containerAlt}>
    <Image source={{ uri: item.icon }} style={styles.iconStyle} />
    <Text style={styles.titleStyle}>{item.label}</Text>
    <Switch
      trackColor={{ false: '#EFEFEF', true: '#34C759' }}
      thumbColor={'#FFFFFF'}
      onValueChange={() => toggleSwitch(item.id)}
      value={item.isActive}
    />
  </View>
))}
Enter fullscreen mode Exit fullscreen mode

Submitting Selected Interests

When the user presses the Submit button, we filter out the active switches and display them.

const handleSubmit = () => {
  const activeLabels = switches.filter(item => item.isActive).map(item => item.label);
  setDisplayText(activeLabels);
};
Enter fullscreen mode Exit fullscreen mode

The handleSubmit function ensures that selected interests are stored and displayed efficiently.


Styling the Component

We enhance the user experience with a clean UI:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#121212',
  },
  containerAlt: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#1E1E1E',
    borderRadius: 10,
    padding: 12,
    marginBottom: 10,
  },
  button: {
    backgroundColor: '#4A90E2',
    padding: 15,
    borderRadius: 50,
  },
  buttonText: {
    color: '#FFFFFF',
    fontSize: 17,
    fontWeight: '600',
  },
  titleStyle: {
    color: '#fff',
    padding: 30,
  },
});
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Handling multiple switches in React Native is simple with efficient state management. By following this approach, you can create interactive UI elements that enhance user engagement. This technique is useful for various applications, including settings screens, preference selections, and more.

Give it a try in your next project and customize it to suit your needs! 🚀

Top comments (0)