React-native switch :
Switch is available in both android and iOS. This component is mainly used to add one turn on/off feature in Mobile apps. React-native provides one switch component with a couple of different props. In this tutorial, we will learn how to use this component and its props.
Create a basic react-native project :
Create one basic react-native project using npx react-native init SampleProgram. It will create one new react-native project in a folder SampleProgram. Open that folder, edit App.js as like below and run it on Android or iOS device/simulator/emulator :
import React from 'react';
import {
SafeAreaView,
StatusBar,
Switch,
StyleSheet,
View
} from 'react-native';
const App = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<View style={styles.container}>
<Switch />
</View>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
container: {
alignItems: "center",
justifyContent: "center"
}
});
export default App;
It will look like below :
Here, you can see one switch on top. Try to click and activate it. It will not work. Because, by default, react-native doesn’t provide a clickable component.
We need to write custom code to make this work.
With the latest react-native version, you can use hook :
First of all, import useState :
import React, {useState} from 'react';
And write a toggle function :
const App = () => {
const [switchState, setSwitchState] = useState(false);
const toggleSwitch = () => setSwitchState(switchState => !switchState);
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<View style={styles.container}>
<Switch value={switchState} onValueChange={toggleSwitch}/>
</View>
</SafeAreaView>
</>
);
};
That’s it. It will work. You can click on the switch to toggle.
Props :
We have used two props value and onValueChange props in the above example. React native provides a couple of different props to change different properties of a switch :
disabled :
true will disable the switch. The default value is false.
ios_backgroundColor :
It takes one color to set the background of the switch. This is available only for iOS.
onChange :
Function that invokes when the user tries to change the switch value. It receives an event.
thumbColor :
It is the color of the foreground color grip.
trackColor :
Custom color of the switch track.
value :
The value of the switch. Default false. true will turn it on.
onValueChange :
Function that invokes when the user changes the state of the switch. It receives a new value.