Open In App

Create a Currency Converter using React-Native

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will build a currency converter using react native. This app serves as a valuable tool for travelers, business professionals, and anyone who frequently deals with international currencies. It enables users to effortle­ssly convert one currency to another.

Preview of final output: Let us have a look at how the final output will look like.

Create-a-Currency-Converter-using-React-Native

Prerequisites:

Approach:

In this approach, we’ll create a user-friendly currency conversion UI with input fields, dropdowns for currency selection, a conversion button, and real-time exchange rate data from exchange­rate-exchangerate-api.com. A currency-swapping feature will be added, and conversion details will be displayed upon completion.

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
    "react-native-paper": "4.9.2",
    "@expo/vector-icons": "^13.0.0",
    "react-native-modal-dropdown": "*"
}

Example: Write the following code in respective files.

  • App.js: This file implements all the functionalities and renders the component
  • styles.js: This file contains the styling for the components

Javascript




import React, {
  useState, useEffect, useCallback
} from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet
} from "react-native";
import ModalDropdown from
  "react-native-modal-dropdown";
import { styles } from "./Style";
 
const App = () => {
  const [amount, setAmount] =
    useState("");
  const [fromCurrency, setFromCurrency] =
    useState("USD");
  const [toCurrency, setToCurrency] =
    useState("EUR");
  const [currencies, setCurrencies] =
    useState([]);
  const [convertedAmount, setConvertedAmount] =
    useState(null);
 
  const convertCurrency =
    useCallback(() => {
      if (!amount) {
        setConvertedAmount(null);
        return;
      }
      fetch(`
https://api.exchangerate-api.com/v4/latest/${fromCurrency}
        `)
        .then((response) => response.json())
        .then((data) => {
          const exchangeRates =
            data.rates;
          const conversionRate =
            exchangeRates[toCurrency];
 
          if (conversionRate) {
            const result =
              parseFloat(amount) * conversionRate;
            setConvertedAmount(result.toFixed(2));
          } else {
            setConvertedAmount("Invalid Currency ");
          }
        })
        .catch((error) => {
          console.error("Error converting currency: ", error
          );
        });
    }, [amount, fromCurrency, toCurrency]);
 
  useEffect(() => {
    fetch(`
https://api.exchangerate-api.com/v4/latest/USD
      `)
      .then((response) =>
        response.json())
      .then((data) => {
        const currencyList =
          Object.keys(data.rates);
        setCurrencies(currencyList);
      })
      .catch((error) => {
        console.error(" Error fetching currency data: ",
          error);
      });
  }, []);
 
  useEffect(() => {
    convertCurrency();
  }, [convertCurrency]);
 
  const swapCurrencies = () => {
    // Swap the selected currencies
    setFromCurrency(toCurrency);
    setToCurrency(fromCurrency);
  };
 
  return (
    <View style={styles.container}>
      <View style={styles.subcontainer}>
        <Text style={styles.header}>
          Currency Converter</Text>
        <Text style={styles.label}>Amount:</Text>
        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            value={amount}
            onChangeText={(text) => setAmount(text)}
            keyboardType="numeric"
            placeholder="Enter amount"
            placeholderTextColor="#999"
          />
        </View>
        <Text style={styles.label}>
          From Currency:
        </Text>
        <View style={styles.inputContainer}>
          <ModalDropdown
            style={styles.dropdown}
            options={currencies}
            defaultValue={fromCurrency}
            onSelect={(index, value) =>
              setFromCurrency(value)}
          />
        </View>
        <TouchableOpacity
          style={styles.swapButton}
          onPress={swapCurrencies}>
          <Text style={styles.swapButtonText}>
              &#8646;
          </Text>
        </TouchableOpacity>
        <Text style={styles.label}>
          To Currency:
        </Text>
        <View style={styles.inputContainer}>
          <ModalDropdown
            style={styles.dropdown}
            options={currencies}
            defaultValue={toCurrency}
            onSelect={(index, value) =>
              setToCurrency(value)}
          />
        </View>
 
        <TouchableOpacity
          style={styles.convertButton}
          onPress={convertCurrency}
        >
          <Text style={styles.convertButtonText}>
            Convert
          </Text>
        </TouchableOpacity>
 
        {convertedAmount !== null && (
          <Text style={styles.result}>
            {amount} {fromCurrency} is
            {convertedAmount} {toCurrency}
          </Text>
        )}
      </View>
    </View>
  );
};
 
export default App;


Javascript




//styles.js
 
import { StyleSheet } from "react-native";
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#f5f5f5"
  },
  subcontainer: {
    shadowColor: "rgba(0, 0, 0, 0.2)",
    shadowOffset: {
      width: 0,
      height: 6
    },
    shadowOpacity: 1,
    shadowRadius: 15,
    elevation: 5,
    padding: 40,
    borderRadius: 20,
    backgroundColor: "#ffffff"
  },
  header: {
    fontSize: 28,
    fontWeight: "bold",
    marginBottom: 20,
    color: "green"
  },
  inputContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginVertical: 10
  },
  label: {
    fontSize: 19,
    marginRight: 10,
    color: "#333",
    fontFamily: "Pacifico"
  },
  input: {
    flex: 1,
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 10,
    paddingHorizontal: 10,
    height: 40,
    color: "#333"
  },
  dropdown: {
    width: 150,
    height: 40,
    borderWidth: 1,
    borderColor: "#ccc",
    borderRadius: 4,
    paddingHorizontal: 10,
    justifyContent: "center",
    color: "#333"
  },
  convertButton: {
    backgroundColor: "#007BFF",
    borderRadius: 4,
    paddingVertical: 12,
    paddingHorizontal: 24,
    marginTop: 20,
    shadowColor: "rgba(0, 123, 255, 0.5)",
    shadowOffset: {
      width: 0,
      height: 3
    },
    shadowOpacity: 1,
    shadowRadius: 15,
    elevation: 3
  },
  convertButtonText: {
    color: "white",
    fontSize: 18,
    fontWeight: "bold",
    textAlign: "center"
  },
  result: {
    marginTop: 20,
    fontSize: 18,
    color: "#333"
  },
  swapButton: {
    backgroundColor: "#ddd",
    borderRadius: 50,
    width: 45,
    height: 40,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 10
  },
  swapButtonText: {
    fontSize: 30,
    textAlign: "center",
    color: "red",
    marginBottom: 10
  }
});
 
export { styles };


Steps to Run:

Step 1: To run react native application use the following command:

npx expo start

Step 2: Depending on your operating system type the following command

  • To run on Android:
npx react-native run-android
  • To run on iOS:
npx react-native run-ios

Output:

Create-a-Currency-Converter-using-React-Native



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads