Build a Simple React JS Interactive Web-Based Conversion Rate Calculator: A Beginner’s Guide

In today’s interconnected world, dealing with different currencies is a common occurrence. Whether you’re planning a trip abroad, managing international finances, or simply browsing online stores, you’ll likely need to convert currencies. Manually calculating these conversions can be tedious and prone to errors. This is where a currency conversion rate calculator comes in handy. In this tutorial, we will build a simple, interactive currency conversion rate calculator using React JS. This project is perfect for beginners and intermediate developers looking to deepen their understanding of React and create a useful tool.

Why Build a Currency Converter?

Creating a currency converter in React offers several benefits:

  • Practicality: It’s a useful tool for everyday tasks, making it a valuable addition to your portfolio.
  • Learning Opportunity: It provides a hands-on experience with React components, state management, and API interactions.
  • Skill Enhancement: It helps you solidify your understanding of fundamental React concepts and improve your coding skills.

Prerequisites

Before you start, make sure you have the following:

  • Node.js and npm (or yarn) installed: These are essential for managing project dependencies.
  • A basic understanding of HTML, CSS, and JavaScript: Familiarity with these languages is crucial for understanding the code.
  • A code editor: VS Code, Sublime Text, or any other editor of your choice.

Setting Up the Project

Let’s get started by setting up our React project. Open your terminal and run the following command:

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

This command creates a new React application named “currency-converter” and navigates you into the project directory.

Project Structure

Our project will have a simple structure. Inside the src directory, we’ll focus on these files:

  • App.js: This is the main component where we’ll build our calculator.
  • App.css: This file will hold the styles for our calculator’s appearance.

Fetching Currency Exchange Rates

To perform currency conversions, we need real-time exchange rates. We’ll use a free and open API for this purpose. There are several APIs available; for this tutorial, we’ll use ExchangeRate-API. Sign up to get an API key (it’s free!).

Once you have your API key, let’s create a function to fetch the exchange rates. We’ll add this function within our App.js file.

import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [currencies, setCurrencies] = useState([]);
  const [fromCurrency, setFromCurrency] = useState('USD');
  const [toCurrency, setToCurrency] = useState('EUR');
  const [amount, setAmount] = useState(1);
  const [exchangeRate, setExchangeRate] = useState(1);
  const [convertedAmount, setConvertedAmount] = useState(0);

  const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
  const BASE_URL = 'https://v6.exchangerate-api.com/v6/';

  useEffect(() => {
    async function fetchCurrencies() {
      try {
        const response = await fetch(`${BASE_URL}${API_KEY}/codes`);
        const data = await response.json();
        if (data.result === 'success') {
          setCurrencies(data.supported_codes.map(code => code[0]));
        }
      } catch (error) {
        console.error('Error fetching currencies:', error);
      }
    }

    fetchCurrencies();
  }, []);

  useEffect(() => {
    async function fetchExchangeRate() {
      try {
        const response = await fetch(`${BASE_URL}${API_KEY}/pair/${fromCurrency}/${toCurrency}`);
        const data = await response.json();
        if (data.result === 'success') {
          setExchangeRate(data.conversion_rate);
          setConvertedAmount(amount * data.conversion_rate);
        }
      } catch (error) {
        console.error('Error fetching exchange rate:', error);
      }
    }

    fetchExchangeRate();
  }, [fromCurrency, toCurrency, amount]);

  function handleAmountChange(e) {
    setAmount(e.target.value);
  }

  function handleFromCurrencyChange(e) {
    setFromCurrency(e.target.value);
  }

  function handleToCurrencyChange(e) {
    setToCurrency(e.target.value);
  }

  return (
    // ... (rest of the component)
  );
}

export default App;

Let’s break down this code:

  • Import statements: We import the necessary modules from React.
  • State variables:
    • currencies: An array to store the available currency codes.
    • fromCurrency: The currency to convert from (e.g., USD).
    • toCurrency: The currency to convert to (e.g., EUR).
    • amount: The amount to convert.
    • exchangeRate: The current exchange rate.
    • convertedAmount: The converted amount.
  • API Key and Base URL: Replace 'YOUR_API_KEY' with your actual API key.
  • useEffect hook (currencies): This hook fetches the list of supported currencies from the API when the component mounts.
  • useEffect hook (exchange rate): This hook fetches the exchange rate whenever fromCurrency, toCurrency, or amount changes.
  • Event Handlers: These functions update the state variables when the user interacts with the input fields and select boxes.

Building the User Interface (UI)

Now, let’s create the UI for our currency converter within the App.js file. We’ll use HTML elements like input fields, select boxes, and labels to build the interface.

import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
  const [currencies, setCurrencies] = useState([]);
  const [fromCurrency, setFromCurrency] = useState('USD');
  const [toCurrency, setToCurrency] = useState('EUR');
  const [amount, setAmount] = useState(1);
  const [exchangeRate, setExchangeRate] = useState(1);
  const [convertedAmount, setConvertedAmount] = useState(0);

  const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
  const BASE_URL = 'https://v6.exchangerate-api.com/v6/';

  useEffect(() => {
    async function fetchCurrencies() {
      try {
        const response = await fetch(`${BASE_URL}${API_KEY}/codes`);
        const data = await response.json();
        if (data.result === 'success') {
          setCurrencies(data.supported_codes.map(code => code[0]));
        }
      } catch (error) {
        console.error('Error fetching currencies:', error);
      }
    }

    fetchCurrencies();
  }, []);

  useEffect(() => {
    async function fetchExchangeRate() {
      try {
        const response = await fetch(`${BASE_URL}${API_KEY}/pair/${fromCurrency}/${toCurrency}`);
        const data = await response.json();
        if (data.result === 'success') {
          setExchangeRate(data.conversion_rate);
          setConvertedAmount(amount * data.conversion_rate);
        }
      } catch (error) {
        console.error('Error fetching exchange rate:', error);
      }
    }

    fetchExchangeRate();
  }, [fromCurrency, toCurrency, amount]);

  function handleAmountChange(e) {
    setAmount(e.target.value);
  }

  function handleFromCurrencyChange(e) {
    setFromCurrency(e.target.value);
  }

  function handleToCurrencyChange(e) {
    setToCurrency(e.target.value);
  }

  return (
    <div>
      <h1>Currency Converter</h1>
      <div>
        <div>
          <label>Amount:</label>
          
        </div>
        <div>
          <label>From:</label>
          
            {currencies.map(currency => (
              
                {currency}
              
            ))}
          
        </div>
        <div>
          <label>To:</label>
          
            {currencies.map(currency => (
              
                {currency}
              
            ))}
          
        </div>
        <div>
          <p>Converted Amount: {convertedAmount.toFixed(2)} {toCurrency}</p>
          <p>Exchange Rate: {exchangeRate.toFixed(4)}</p>
        </div>
      </div>
    </div>
  );
}

export default App;

Here’s a breakdown of the UI code:

  • Container: We use a div with the class container to wrap the entire calculator.
  • Heading: An h1 tag for the title.
  • Converter Div: A div with the class converter will hold the input fields, select boxes, and result display.
  • Amount Input: An input field of type “number” for the user to enter the amount to convert.
  • Currency Select Boxes: Two select elements for selecting the “from” and “to” currencies. We populate these with options generated from the currencies state variable.
  • Result Display: Displays the converted amount and the exchange rate.
  • Event Handlers: handleAmountChange, handleFromCurrencyChange, and handleToCurrencyChange are used to update the state when the user interacts with the UI.

Styling the Calculator (CSS)

To make the calculator visually appealing, we’ll add some CSS styles. Open App.css and add the following code:


.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f0f0;
  font-family: sans-serif;
}

.converter {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.15);
  width: 80%;
  max-width: 400px;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.input-group, .select-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

input[type="number"], select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

.result {
  margin-top: 20px;
  text-align: center;
  font-size: 18px;
  color: #333;
}

This CSS code will:

  • Center the calculator on the page.
  • Style the input field, select boxes, and labels.
  • Add a box shadow for a modern look.
  • Improve readability.

Running the Application

To run your application, use the following command in your terminal within the project directory:

npm start

This will start the development server, and your currency converter will be accessible in your web browser (usually at http://localhost:3000/).

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • API Key Error:
    • Problem: The exchange rate API might return an error if your API key is incorrect or invalid.
    • Solution: Double-check your API key and ensure it’s correctly entered in the API_KEY variable. Also, verify that your API key has the necessary permissions.
  • CORS Errors:
    • Problem: Your browser may block requests to the API due to Cross-Origin Resource Sharing (CORS) restrictions.
    • Solution: If you encounter CORS errors, you might need to use a proxy server or configure your development environment to bypass CORS restrictions. For development, a simple solution is to use a CORS proxy extension in your browser. For production, you’ll need to configure your server to handle CORS.
  • Incorrect Data Display:
    • Problem: The converted amount might not be displaying correctly, or the exchange rate could be wrong.
    • Solution: Double-check the logic in your useEffect hook to ensure the exchange rate is being fetched correctly and the conversion calculation is accurate. Also, ensure the state variables are updated correctly when the user interacts with the UI.
  • Currency List Not Loading:
    • Problem: The currency select boxes might be empty because the list of currencies isn’t being fetched or loaded correctly.
    • Solution: Check the fetchCurrencies function and make sure the API call is successful and that the setCurrencies function is updating the state correctly. Also, verify that the currencies state variable is being used to populate the select options.

Key Takeaways

  • You’ve successfully built a simple but functional currency converter using React.
  • You’ve learned how to fetch data from an external API and use it to update the UI.
  • You’ve gained practical experience with React components, state management, and event handling.
  • You’ve understood how to structure a React project and add CSS styles.

Enhancements and Next Steps

This is a starting point. Here are some ideas to enhance your currency converter:

  • Error Handling: Implement error handling to gracefully handle API errors or invalid user input.
  • Currency Symbols: Display currency symbols alongside the converted amounts.
  • User Interface Improvements: Add more styling to improve the UI.
  • Save Conversion History: Implement a feature to save the conversion history.
  • Add More Features: Add more currencies, or allow the user to define their own custom currencies.

FAQ

Here are some frequently asked questions:

  1. How do I get an API key for the currency exchange rate?

    You can sign up for a free API key from a provider like ExchangeRate-API. The process typically involves creating an account and obtaining an API key from your dashboard.

  2. Why am I getting CORS errors?

    CORS (Cross-Origin Resource Sharing) errors occur when your browser blocks requests to an external API. This is a security measure. You can resolve this by using a CORS proxy during development or configuring CORS headers on your server for production.

  3. Can I use a different API for exchange rates?

    Yes, you can use any other currency exchange rate API. You’ll need to modify the API endpoint and data parsing logic in your code accordingly.

  4. How do I deploy this application?

    You can deploy your React application to platforms like Netlify, Vercel, or GitHub Pages. These platforms provide free hosting and easy deployment options.

  5. What are the benefits of using React for this project?

    React allows you to build a dynamic and interactive user interface. It simplifies the process of updating the UI based on user interactions and data changes. React also promotes code reusability and maintainability.

Building this currency converter has equipped you with valuable skills in React development. You’ve seen how to combine state management, API interaction, and UI design to create a practical application. As you continue to explore React, remember that practice is key. Experiment with new features, try different APIs, and don’t be afraid to make mistakes – that’s how you learn. Keep building, keep coding, and your skills will steadily improve. The world of front-end development is constantly evolving, so embrace the learning process, stay curious, and continue to build amazing things.