Getting Started with React Native: Taking input from the user

Getting Started with React Native: Taking input from the user

Here in this blog, I would be discussing how to take input from the user and how I build a simple currency converter in react native. So, let's open our snack powered by the expo, now in this project, I would be using Alert, SafeAearView, and ScrollView. The alert helps us to notify the user, SafeAreaView places our content in such a way that it is safe from the notch and cuts of the fancy screens. and why ScrollAreaView? well, we would be taking input from the user here, SafeAreaView has a special prop keyboardDismissMode which when set to true m, helps to exit the keyboard when the user taps anywhere on the screen.

Also, we would be taking input from the user and using the state to update that input in one go. So we would be using the useState hook here as well.

import React ,{useState} from 'react';
import { StyleSheet, Text, View ,SafeAreaView ,ScrollView ,TextInput, TouchableOpacity ,Alert} from 'react-native';

now since it is a currency converter app we need to get values from somewhere, so I would be making an object and later mapping through each value.

  {Object.keys(currencyPerRuppe).map((currency)=>(
    <TouchableOpacity key={currency} style={styles.currencyButton} onPress={()=>buttonPress(currency)}
    ><Text style={styles.currencyText}>{currency}</Text></TouchableOpacity>
  ))}

now, I would be working on the input part, I have used the use of the state hook and set the initial value to 0. now I would be taking value from the TextInput and finally updating the value to using setState. Also, text input provides us the option to change the keyboard type, and do remember to set the keyboard to dismiss mode as true in the scroll view.

  <TextInput style={styles.inputValue} keyboardType="numeric" 
          placeholderTextColor="#c1c1c1" placeholder="Value"
          value={inputValue} onChangeText={(inputValue)=> setInputValue(inputValue)}          
          ></TextInput>

now finally we just need to calculate the converted value of the currency on the button press, so I would be making a function to do that also we need to handle an expectation what if the user pressed the button without entering any value? well, we can check that and give an alert to the user.

const buttonPress = (currency) => {
    if(!inputValue){

      Alert.alert(
        "Please enter a correct value",
        "Enter a numeric value",
        [

          { text: "OK", onPress: () => console.log("OK Pressed") }
        ],
      );
    }
    let result = parseFloat(inputValue) * currencyPerRuppe[currency] ;
     setResultValue(result.toFixed(2));
   }

here the snack of this app, if you want to check the whole app or code.

wow! so you read the whole article man!! who does that.. get a life man.

Did you find this article valuable?

Support Gaurav Tewari by becoming a sponsor. Any amount is appreciated!