How to Add a Switch Toggle Button in React Native

Last Updated on December 15, 2020.

A toggle button is extremely useful when the user needs to give boolean input such as Yes or No. The switch component is used to create a switch/toggle button in react native. In this blog post, let’s check how to add a switch button in your react native project.

 <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor="#f5dd4b"
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />

The implementation of the toggle button is pretty straight as given above. The component works according to the value and onValueChange props. The trackColor, thumbColor and ios_backgroundColor props are used for styling the switch button.

Following is the complete example of react native switch button. Go through it for proper understanding.

Class Component

import React, {Component} from 'react';
import {View, Switch, StyleSheet} from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      toggle: false,
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Switch
          trackColor={{false: 'gray', true: 'teal'}}
          thumbColor="white"
          ios_backgroundColor="gray"
          onValueChange={(value) => this.setState({toggle: value})}
          value={this.state.toggle}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

Function Component

import React, {useState} from 'react';
import {View, Switch, StyleSheet} from 'react-native';

const App = () => {
  const [toggle, setToggle] = useState(false);

  return (
    <View style={styles.container}>
      <Switch
        trackColor={{false: 'gray', true: 'teal'}}
        thumbColor="white"
        ios_backgroundColor="gray"
        onValueChange={(value) => setToggle(value)}
        value={toggle}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

export default App;

Have a look at the output of react native toggle button example.

I hope this react native tutorial helped you!

Leave a Reply

%d bloggers like this: