Build an Awesome Currency Converter App with React.js

Build an Awesome Currency Converter App with React.js

Table of Contents

  1. Introduction
  2. Setting up the app
  3. Creating the currency input component
  4. Fetching currency rates from the API
  5. Updating the amount and currency
  6. Handling currency and amount changes
  7. Formatting the numbers
  8. Styling the app
  9. Conclusion

Introduction

In this tutorial, I will show you how to create an awesome currency converter app with React.js. The app will use the Fixer.io API to fetch the latest currency rates and will be responsive, so any changes made in one input will update the corresponding value in real-time. We will start with an empty React app and gradually build it up to a fully functional currency converter.

Pros:

  • Real-time currency conversion.
  • Responsive design.
  • Use of React.js.

Cons:

  • Requires integration with an external API.
  • Requires basic knowledge of React.js.

Setting up the app

To start off, we need to set up a new React app. Open your terminal and run the following command:

npx create-react-app currency-converter

This will create a new directory called "currency-converter" with all the necessary files for a React app. Next, navigate into the directory by running:

cd currency-converter

Now we're ready to start building our currency converter app.

Creating the currency input component

In this section, we will create a new component called CurrencyInput that will handle the input and select elements for each currency.

import React from 'react';

function CurrencyInput(props) {
  return (
    <div className="input-group">
      <input type="number" value={props.amount} onChange={props.onAmountChange} />
      <select value={props.currency} onChange={props.onCurrencyChange}>
        {props.currencies.map(currency => (
          <option value={currency} key={currency}>{currency}</option>
        ))}
      </select>
    </div>
  );
}

export default CurrencyInput;

Fetching currency rates from the API

To fetch the latest currency rates from the Fixer.io API, we will use the useEffect hook from React.

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
  const [rates, setRates] = useState([]);

  useEffect(() => {
    axios.get('https://api.fixer.io/latest')
      .then(response => {
        setRates(Object.keys(response.data.rates));
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  return (
    // App content goes here
  );
}

export default App;

Updating the amount and currency

Now that we have fetched the currency rates from the API, we can update the amount and currency inputs.

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import CurrencyInput from './CurrencyInput';

function App() {
  const [rates, setRates] = useState([]);
  const [amountOne, setAmountOne] = useState(1);
  const [amountTwo, setAmountTwo] = useState(1);
  const [currencyOne, setCurrencyOne] = useState('USD');
  const [currencyTwo, setCurrencyTwo] = useState('EUR');

  useEffect(() => {
    axios.get('https://api.fixer.io/latest')
      .then(response => {
        setRates(Object.keys(response.data.rates));
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  const handleAmountOneChange = (event) => {
    const newAmountOne = parseFloat(event.target.value);
    setAmountOne(newAmountOne);
    setAmountTwo(newAmountOne * (rates[currencyTwo] / rates[currencyOne]));
  };

  const handleAmountTwoChange = (event) => {
    const newAmountTwo = parseFloat(event.target.value);
    setAmountTwo(newAmountTwo);
    setAmountOne(newAmountTwo * (rates[currencyOne] / rates[currencyTwo]));
  };

  const handleCurrencyOneChange = (event) => {
    const newCurrencyOne = event.target.value;
    setCurrencyOne(newCurrencyOne);
    setAmountTwo(amountOne * (rates[currencyTwo] / rates[newCurrencyOne]));
  };

  const handleCurrencyTwoChange = (event) => {
    const newCurrencyTwo = event.target.value;
    setCurrencyTwo(newCurrencyTwo);
    setAmountOne(amountTwo * (rates[newCurrencyTwo] / rates[currencyOne]));
  };

  return (
    <div className="app">
      <h1 className="app-title">Currency Converter</h1>
      <div className="input-container">
        <CurrencyInput
          amount={amountOne}
          currency={currencyOne}
          currencies={rates}
          onAmountChange={handleAmountOneChange}
          onCurrencyChange={handleCurrencyOneChange}
        />
        <CurrencyInput
          amount={amountTwo}
          currency={currencyTwo}
          currencies={rates}
          onAmountChange={handleAmountTwoChange}
          onCurrencyChange={handleCurrencyTwoChange}
        />
      </div>
    </div>
  );
}

export default App;

Handling currency and amount changes

To handle changes to the currency and amount inputs, we will create separate functions for each input.

const handleAmountOneChange = (event) => {
  const newAmountOne = parseFloat(event.target.value);
  setAmountOne(newAmountOne);
  setAmountTwo(newAmountOne * (rates[currencyTwo] / rates[currencyOne]));
};

const handleAmountTwoChange = (event) => {
  const newAmountTwo = parseFloat(event.target.value);
  setAmountTwo(newAmountTwo);
  setAmountOne(newAmountTwo * (rates[currencyOne] / rates[currencyTwo]));
};

const handleCurrencyOneChange = (event) => {
  const newCurrencyOne = event.target.value;
  setCurrencyOne(newCurrencyOne);
  setAmountTwo(amountOne * (rates[currencyTwo] / rates[newCurrencyOne]));
};

const handleCurrencyTwoChange = (event) => {
  const newCurrencyTwo = event.target.value;
  setCurrencyTwo(newCurrencyTwo);
  setAmountOne(amountTwo * (rates[newCurrencyTwo] / rates[currencyOne]));
};

Formatting the numbers

To make the numbers easier to read, we can format them using the toFixed method.

const formatNumber = (number) => {
  return number.toFixed(2);
};

// Inside the handle functions
setAmountOne(formatNumber(newAmountOne));
setAmountTwo(formatNumber(newAmountTwo));

Styling the app

Let's add some basic styling to make the app look better.

body {
  background-color: #161616;
  color: #ddd;
  padding: 20px;
}

.app-title {
  font-weight: bold;
  color: #fef;
}

.input-container {
  display: grid;
  grid-template-columns: 100px 80px;
  gap: 20px;
}

.input-group {
  background-color: #335;
  width: 180px;
  margin: 0 auto 20px;
  border-radius: 15px;
  display: grid;
  grid-template-columns: 1fr;
}

.input-group input,
.input-group select {
  background: none;
  border: 0;
  color: #fff;
  padding: 15px;
}

.input-group select {
  padding-left: 10px;
}

input::-webkit-inner-spin-button,
input::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input[type="number"] {
  -moz-appearance: textfield;
}

Conclusion

In this tutorial, we have created an awesome currency converter app using React.js. We have covered setting up the app, creating the currency input component, fetching currency rates from the API, updating the amount and currency inputs, handling currency and amount changes, formatting the numbers, and styling the app. Feel free to customize the app further and add more features to enhance its functionality.

FAQ

Q: How can I add more currencies to the converter?

To add more currencies to the converter, you can modify the https://api.fixer.io/latest endpoint to include additional currencies. You can also update the rates state to include the new currency rates.

Q: Can I use this currency converter app in my own project?

Yes, you can use this currency converter app in your own project. Simply copy the relevant code and modify it to fit your project's requirements.

Q: Can I style the app further to match my own design?

Definitely! The provided styling is just a basic layout. Feel free to customize the CSS styles to match your own design preferences.

Q: Are there any limitations to using the Fixer.io API?

The Fixer.io API has certain limitations depending on the type of subscription you have. The free plan has some limitations on the number of requests per month and the availability of certain features. Make sure to check their documentation for more details.

Q: Is this app responsive and mobile-friendly?

Yes, the app is designed to be responsive and should work well on different devices and screen sizes. However, you may need to tweak the CSS styles to optimize the layout for smaller screens.

Q: Can I integrate this currency converter with other APIs or services?

Yes, you can integrate this currency converter with other APIs or services to enhance its functionality. For example, you could add additional features such as historical currency data or currency exchange notifications.

I am a shopify merchant, I am opening several shopify stores. I use ppspy to find Shopify stores and track competitor stores. PPSPY really helped me a lot, I also subscribe to PPSPY's service, I hope more people can like PPSPY! — Ecomvy

Join PPSPY to find the shopify store & products

To make it happen in 3 seconds.

Sign Up
App rating
4.9
Shopify Store
2M+
Trusted Customers
1000+
No complicated
No difficulty
Free trial