React Native Switch Case Statement Tutorial

04-Apr-2023

.

Admin

React Native Switch Case Statement Tutorial

Hi Guys,

In this tutorial, I will explain you how to use switch case statement in react native. You can easily use switch case statement in react native. First i will create function checkSwitch


, after I will show switch case statement using react native.

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

Step 1 - Create project

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

expo init SwitchCaseStatement

Step 2 - App.js

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

import React, { Component } from 'react';

import { Platform, StyleSheet, View, TextInput, TouchableOpacity, Alert, Text } from 'react-native';

export default class App extends Component {

constructor(){

super();

this.state={

TextInput_Data : ''

}

}

checkSwitch=(param)=>{

switch(param) {

case '1':

this.One();

break;

case '2':

this.Two();

break;

case '3':

this.Three();

break;

case '4':

this.Four();

break;

case '5':

this.Five();

break;

default:

Alert.alert("NUMBER NOT FOUND");

}

}

One=()=>{

Alert.alert("One");

}

Two=()=>{

Alert.alert("Two");

}

Three=()=>{

Alert.alert("Three");

}

Four=()=>{

Alert.alert("Four");

}

Five=()=>{

Alert.alert("Five");

}

render() {

return (

<View style={styles.MainContainer}>

<TextInput

placeholder="Enter Number"

onChangeText={data => this.setState({ TextInput_Data: data })}

style={styles.textInputStyle}

keyboardType = {"numeric"}

/>

<TouchableOpacity onPress={this.checkSwitch.bind(this, this.state.TextInput_Data)} activeOpacity={0.6} style={styles.button} >

<Text style={styles.TextStyle}> Click </Text>

</TouchableOpacity>

</View>

);

}

}

const styles = StyleSheet.create({

MainContainer: {

flex: 1,

justifyContent: 'center',

alignItems: 'center',

},

textInputStyle: {

height: 40,

width: '80%',

textAlign: 'center',

borderWidth: 1,

borderColor: '#008b8b',

marginBottom: 15

},

button: {

width: '80%',

padding: 8,

backgroundColor: '#008b8b',

borderRadius:5,

justifyContent: 'center',

alignItems: 'center'

},

TextStyle:{

color:'#fff',

}

});

Step 3 - Run project

In the last step run your project using bellow command.

npm start

Output

It will help you...

#React Native