How To Create Switch In React Native?

May 05, 2021 . Admin

Hi Dev,

How To Create Switch In React Native?

Today, I will explain you how to create switch in react native. You can easily create switch in react native. First i will import namespace Switch

, after I will make switch using Switch tag in react native.

Here, I will give you full example for simply display switch using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init switch 
Step 2 - App.js

In this step, You will open App.js file and put the code.

import React, { useState } from "react";
import { Text, StyleSheet,TextInput,View ,Switch } from 'react-native';
import { Provider ,Appbar, Avatar } from 'react-native-paper';

const MyComponent = () => {

  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  const _goBack = () => console.log('Went back');

  const _handleSearch = () => console.log('Searching');

  const _handleMore = () => console.log('Shown more');

  return (
    <Provider>
    <Appbar.Header style={styles.header}>
      <Appbar.BackAction onPress={_goBack} />
      <Appbar.Content title="Mywebtuts" subtitle="Subtitle" />
      <Appbar.Action icon="magnify" onPress={_handleSearch} />
      <Appbar.Action icon="dots-vertical" onPress={_handleMore} />
    </Appbar.Header>
      <View style={styles.mainbox}>
        <Text style={styles.textstyle}>React Native Switch Example</Text>
        <Switch
        style={styles.swichstyle}
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
      </View>
    </Provider>
  );
};


const styles = StyleSheet.create({
  title:{
    margin: 10,
    fontSize: 15,
    fontSize: 35
  },
  mainbox:{
    textAlign:'center',
    flex: 0.8,
    alignItems: "center",
    justifyContent: "center",
  },
  textstyle:{
    fontSize: 25,
    marginBottom: 20,
  }
});
export default MyComponent;
Step 3 - Run project In the last step run your project using bellow command.
npm start
Output

It will help you...

#React Native