Browse 800+ Public APIs

Building a Currency Conversion Tool with Fixer Real-Time API

2 years ago

In today's globalized world, understanding and managing currency conversions is a crucial skill. Whether you're a developer looking to enhance your coding skills or someone interested in building practical tools, creating a currency conversion tool can be a rewarding project. In this blog post, we'll guide you through the process of building a simple yet powerful currency conversion tool using the Fixer real-time API.

Introduction to Fixer API

Fixer.io provides a simple and lightweight API for current and historical foreign exchange rates. It's an excellent choice for developers who need reliable and up-to-date exchange rate information. To get started, you'll need to sign up for a free account on Fixer to obtain your API key.

Setting Up Your Project

Let's start by creating a new React project using Create React App. Open your terminal and run:

npx create-react-app currency-converter
cd currency-converter

Now, install Axios to make HTTP requests:

npm install axios

Creating the Currency Converter Component

Open the src folder and create a new file named CurrencyConverter.js. This component will handle the currency conversion logic using the Fixer API.

// src/CurrencyConverter.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const CurrencyConverter = () => {
  const [forexData, setForexData] = useState(null);
  const [amount, setAmount] = useState(1);
  const [fromCurrency, setFromCurrency] = useState('USD');
  const [toCurrency, setToCurrency] = useState('EUR');
  const [convertedAmount, setConvertedAmount] = useState(null);

  useEffect(() => {
    const apiKey = 'your-fixer-api-key';
    const apiUrl = `http://data.fixer.io/api/latest?access_key=${apiKey}`;

    axios.get(apiUrl)
      .then(response => {
        setForexData(response.data.rates);
      })
      .catch(error => {
        console.error('Error fetching forex rates:', error);
      });
  }, []);

  const convertCurrency = () => {
    if (forexData && forexData[fromCurrency] && forexData[toCurrency]) {
      const rate = forexData[toCurrency] / forexData[fromCurrency];
      const result = amount * rate;
      setConvertedAmount(result.toFixed(2));
    }
  };

  return (
    <div>
      <h1>Currency Converter</h1>
      <div>
        <label>Amount:</label>
        <input
          type="number"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
        />
      </div>
      <div>
        <label>From Currency:</label>
        <select
          value={fromCurrency}
          onChange={(e) => setFromCurrency(e.target.value)}
        >
          {forexData &&
            Object.keys(forexData).map((currency) => (
              <option key={currency} value={currency}>{currency}</option>
            ))}
        </select>
      </div>
      <div>
        <label>To Currency:</label>
        <select
          value={toCurrency}
          onChange={(e) => setToCurrency(e.target.value)}
        >
          {forexData &&
            Object.keys(forexData).map((currency) => (
              <option key={currency} value={currency}>{currency}</option>
            ))}
        </select>
      </div>
      <button onClick={convertCurrency}>Convert</button>
      {convertedAmount && (
        <p>{amount} {fromCurrency} is equal to {convertedAmount} {toCurrency}</p>
      )}
    </div>
  );
};

export default CurrencyConverter;

In this component, we use the useEffect hook to fetch the latest exchange rates when the component mounts. The convertCurrency function calculates the converted amount based on the selected currencies and amount.

Integrating the Currency Converter Component

Now, let's integrate the CurrencyConverter component into our src/App.js:

// src/App.js
import React from 'react';
import CurrencyConverter from './CurrencyConverter';

function App() {
  return (
    <div className="App">
      <CurrencyConverter />
    </div>
  );
}

export default App;

Testing the Currency Converter

Start your development server:

npm start

Visit http://localhost:3000 in your browser, and you should see your currency converter tool. Enter an amount, select the source and destination currencies, and click "Convert" to see the results.

Congratulations! You've just built a currency conversion tool using the Fixer real-time API. This project serves as a great starting point for further enhancements, such as adding additional features or improving the user interface. Explore the Fixer API documentation for more customization options and possibilities.

Feel free to adapt and extend this project to meet your specific requirements. Happy coding!