Skip to content
Related Articles

Related Articles

How to create a Toggle switch in react-native using Material Design library ?

View Discussion
Improve Article
Save Article
  • Last Updated : 10 Mar, 2022

React Native is a framework developed by Facebook for creating native-style apps for iOS & Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UI’s for both platforms.

Approach: In this article, we will see how to create a toggle switch in react-native using material design. We will use react-native-paper library material design to create it. 

In this project, whenever the switch will be toggled, an alert message will appear that will show the status of the switch.

Below is the step by step implementation:

Step 1: Create a project in react-native using the following command:

npx react-native init DemoProject

Step 2: Install react-native paper using the following command:

npm install react-native-paper

Step 3: Create a components folder inside your project. Inside the components folder create a file ToggleSwitch.js

Project Structure: It will look like this.

Example: Write down the code in respective files. In ToggleSwitch.js , we will import Switch Component from ‘react-native-paper’  library .

ToggleSwitch.js




import React, {useState, useEffect} from 'react';
import { Text, View , StyleSheet, Alert} from 'react-native';
import { Switch} from 'react-native-paper' ;
  
const ToggleSwitchExample = () =>{
    const [switchOn, setSwitchOn] = useState(false)
  
    return(
        <View style ={styles.container}>
            <Text>Toggle Switch</Text>
            <Switch value={switchOn} onValueChange={() => {
                setSwitchOn(!switchOn)
                Alert.alert("Switch on : " + !switchOn)} }/>
        </View>
    )
}
  
export default ToggleSwitchExample ;
  
const styles = StyleSheet.create({
     container:{
         padding:45,
         flexDirection:'row',
         justifyContent:'space-around'
     }
})

Now import this file in your App.js file

App.js




import React from 'react';
import type { Node } from 'react';
import { View } from 'react-native';
import ToggleSwitchExample from './components/ToggleSwitch';
  
const App: () => Node = () => {
   return (
      <View>
           
          <ToggleSwitchExample />
       </View>
      
  );
};
  
export default App;

Step to run the application: Run the application using the following command:

npx react-native run-android

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!