DEV Community

Cover image for Build A Currency Converter in ReactJS | Best Beginner ReactJS Project
CodingNepal
CodingNepal

Posted on • Edited on • Originally published at codingnepalweb.com

Build A Currency Converter in ReactJS | Best Beginner ReactJS Project

Build A Currency Converter in ReactJS

Are you new to ReactJS and looking for a project to enhance your skills? Building a currency converter using ReactJS and CSS is an excellent way to do just that. This project reinforces fundamental concepts like components, state management, and API integration, while also providing a practical and rewarding application.

In this blog post, I’ll guide you through building a Currency Converter using ReactJS and pure CSS. In this currency converter, users can input an amount, choose the currencies for conversion, and click a button to get the exchange rate.

Additionally, the converter will display flags representing the currency codes, and users will be able to switch the currencies by clicking a swap button.

Why Build a Currency Converter in ReactJS?

By building this currency converter project using React js and CSS, you can gain the following skills:

  • ReactJS Fundamentals: You’ll get hands-on experience with React components, state management, and hooks.
  • API Integration: Learn how to interact with web services, handle asynchronous operations, and manage data fetching in React.
  • CSS Skills: Learn how to create a responsive and visually appealing UI without relying on pre-built components.
  • Practical Application: This project provides a tangible result that you can showcase in your portfolio or use in real-life scenarios.

Video Tutorial to Build Currency Converter in ReactJS


If you prefer video tutorials, the YouTube video above is a great resource. It explains each line of code and provides comments to make the process of building your ReactJS currency converter easy to follow. If you prefer reading or need a step-by-step guide, keep following this post.

Setting Up the Project

Before we start making the currency converter with ReactJS and CSS, make sure you have Node.js installed on your computer. If you don’t have it, you can download and install it from the official Node.js website.

Create a Project Folder

  • Make a new folder, for instance, “currency-converter”.
  • Open this folder in your VS Code editor.

Initialize the Project

Use Vite to create a new React app with this command:

npm create vite@latest ./ -- --template react
Enter fullscreen mode Exit fullscreen mode

Install Necessary Dependencies:

npm install
Enter fullscreen mode Exit fullscreen mode

Start the Development Server:

npm run dev
Enter fullscreen mode Exit fullscreen mode

If your project is up and running in your browser, congratulations! You’ve successfully set up your project. Now, let’s move on to the next step modifying folders and files.

Modify folder and CSS Files:

  • Remove the default assets folder and App.css file.
  • Download the bg.png image and place it inside the public folder.
  • Replace the content of index.css with the provided code.
/* Import Google Font */
@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Montserrat", sans-serif;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: url("bg.png") #030728 no-repeat center;
}

#root {
  width: 100%;
}

.currency-converter {
  max-width: 410px;
  margin: 0 auto;
  padding: 40px 30px 50px;
  border-radius: 8px;
  backdrop-filter: blur(30px);
  background: rgba(2, 7, 40, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
}

.currency-converter .converter-title {
  color: #fff;
  font-size: 1.65rem;
  font-weight: 600;
  text-align: center;
}

.currency-converter .converter-form {
  margin-top: 45px;
}

.converter-form .form-group {
  display: flex;
  margin-bottom: 30px;
  flex-direction: column;
}

.converter-form .form-group .form-label {
  color: #fff;
  font-weight: 500;
  display: block;
  margin-bottom: 9px;
  font-size: 1rem;
}

.converter-form .form-group .form-input {
  outline: none;
  font-size: 1.1rem;
  padding: 0 15px;
  color: #fff;
  font-weight: 500;
  min-height: 48px;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.converter-form .form-currency-group {
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.form-currency-group .currency-select {
  display: flex;
  padding: 0 10px;
  min-height: 45px;
  align-items: center;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.5);
}

.form-currency-group .currency-select img {
  width: 25px;
}

.form-currency-group .currency-select .currency-dropdown {
  outline: none;
  border: none;
  background: none;
  color: #fff;
  font-size: 1rem;
  font-weight: 500;
  padding: 0 10px 0 5px;
}

.form-currency-group .currency-select .currency-dropdown option {
  color: #000;
  font-weight: 500;
}

.form-currency-group .swap-icon {
  height: 40px;
  width: 40px;
  cursor: pointer;
  display: flex;
  margin-top: 25px;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.5);
  transition: 0.2s ease;
}

.form-currency-group .swap-icon:hover {
  background: rgba(255, 255, 255, 0.3);
}

.converter-form .submit-button {
  width: 100%;
  min-height: 52px;
  border-radius: 6px;
  border: none;
  outline: none;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  margin-top: 5px;
  transition: 0.2s ease;
}

.converter-form .submit-button.loading {
  opacity: 0.7;
  pointer-events: none;
}

.converter-form .submit-button:hover {
  background: rgba(255, 255, 255, 0.7);
}

.converter-form .exchange-rate-result {
  color: #fff;
  font-size: 1.1rem;
  font-weight: 600;
  text-align: center;
  padding: 25px 0;
  margin-top: 25px;
  border-radius: 6px;
  letter-spacing: 0.5px;
  background: rgba(255, 255, 255, 0.15);
}

@media (max-width: 640px) {
  body {
    padding: 0 10px;
  }

  .currency-converter {
    padding: 30px 20px 40px;
  }
}
Enter fullscreen mode Exit fullscreen mode

Creating the Components

Within the src directory of your project, organize your files by creating a “components” folder. Inside the components folder, create the following files:

  • ConverterForm.jsx
  • CurrencySelect.jsx

Adding the Codes

Add the respective code to each newly created file. These files define the layout and functionality of the currency converter.

In components/ConverterForm.jsx, add the code for rendering the converter form, and fetch the exchange rate with an API call.

import { useEffect, useState } from "react";
import CurrencySelect from "./CurrencySelect";

const ConverterForm = () => {
    const [amount, setAmount] = useState(100);
    const [fromCurrency, setFromCurrency] = useState("USD");
    const [toCurrency, setToCurrency] = useState("INR");
    const [result, setResult] = useState("");
    const [isLoading, setIsLoading] = useState(false);

    // Swap the values of fromCurrency and toCurrency
    const handleSwapCurrencies = () => {
        setFromCurrency(toCurrency);
        setToCurrency(fromCurrency);
    }

    // Function to fetch the exchange rate and update the result
    const getExchangeRate = async () => {
        const API_KEY = "PASTE-YOUR-API-KEY";
        const API_URL = `https://v6.exchangerate-api.com/v6/${API_KEY}/pair/${fromCurrency}/${toCurrency}`;

        if (isLoading) return;
        setIsLoading(true);

        try {
            const response = await fetch(API_URL);
            if (!response.ok) throw Error("Something went wrong!");

            const data = await response.json();
            const rate = (data.conversion_rate * amount).toFixed(2);
            setResult(`${amount} ${fromCurrency} = ${rate} ${toCurrency}`);
        } catch (error) {
            setResult("Something went wrong!");
        } finally {
            setIsLoading(false);
        }
    }

    // Handle form submission
    const handleFormSubmit = (e) => {
        e.preventDefault();
        getExchangeRate();
    }

    // Fetch exchange rate on initial render
    // eslint-disable-next-line react-hooks/exhaustive-deps
    useEffect(() => getExchangeRate, []);

    return (
        <form className="converter-form" onSubmit={handleFormSubmit}>
            <div className="form-group">
                <label className="form-label">Enter Amount</label>
                <input
                    type="number"
                    className="form-input"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                    required
                />
            </div>

            <div className="form-group form-currency-group">
                <div className="form-section">
                    <label className="form-label">From</label>
                    <CurrencySelect
                        selectedCurrency={fromCurrency}
                        handleCurrency={e => setFromCurrency(e.target.value)}
                    />
                </div>

                <div className="swap-icon" onClick={handleSwapCurrencies}>
                    <svg width="16" viewBox="0 0 20 19" xmlns="http://www.w3.org/2000/svg">
                        <path d="M19.13 11.66H.22a.22.22 0 0 0-.22.22v1.62a.22.22 0 0 0 .22.22h16.45l-3.92 4.94a.22.22 0 0 0 .17.35h1.97c.13 0 .25-.06.33-.16l4.59-5.78a.9.9 0 0 0-.7-1.43zM19.78 5.29H3.34L7.26.35A.22.22 0 0 0 7.09 0H5.12a.22.22 0 0 0-.34.16L.19 5.94a.9.9 0 0 0 .68 1.4H19.78a.22.22 0 0 0 .22-.22V5.51a.22.22 0 0 0-.22-.22z"
                            fill="#fff" />
                    </svg>
                </div>

                <div className="form-section">
                    <label className="form-label">To</label>
                    <CurrencySelect
                        selectedCurrency={toCurrency}
                        handleCurrency={e => setToCurrency(e.target.value)}
                    />
                </div>
            </div>

            <button type="submit" className={`${isLoading ? "loading" : ""} submit-button`}>Get Exchange Rate</button>
            <p className="exchange-rate-result">
                {/* Display the conversion result */}
                {isLoading ? "Getting exchange rate..." : result}
            </p>
        </form>
    )
}

export default ConverterForm
Enter fullscreen mode Exit fullscreen mode

Remember to paste your API key into the API_KEY variable within the getExchangeRate() function. For security, consider storing your API key in a .env file in your project’s root directory. You can get a free API key from the ExchangeRate-API website.

In components/CurrencySelect.jsx, add the code for rendering the currency selection dropdowns.

// Array of currency codes
const currencyCodes = [
    "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN",
    "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BRL",
    "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF", "CLP", "CNY",
    "COP", "CRC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP",
    "ERN", "ETB", "EUR", "FJD", "FKP", "FOK", "GBP", "GEL", "GGP", "GHS",
    "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF",
    "IDR", "ILS", "IMP", "INR", "IQD", "IRR", "ISK", "JEP", "JMD", "JOD",
    "JPY", "KES", "KGS", "KHR", "KID", "KMF", "KRW", "KWD", "KYD", "KZT",
    "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD",
    "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN",
    "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK",
    "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR",
    "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLE", "SLL", "SOS", "SRD",
    "SSP", "STN", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY",
    "TTD", "TVD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VES",
    "VND", "VUV", "WST", "XAF", "XCD", "XOF", "XPF", "YER", "ZAR", "ZMW",
    "ZWL"
];

const CurrencySelect = ({ selectedCurrency, handleCurrency }) => {
    // Extract the country code from the selected currency code
    const countryCode = selectedCurrency.substring(0, 2);

    return (
        <div className="currency-select">
            <img src={`https://flagsapi.com/${countryCode}/flat/64.png`} alt="Flag" />
            <select
                onChange={handleCurrency}
                className="currency-dropdown"
                value={selectedCurrency}
            >
                {currencyCodes.map(currency => (
                    <option key={currency} value={currency}>{currency}</option>
                ))}
            </select>
        </div>
    )
}

export default CurrencySelect
Enter fullscreen mode Exit fullscreen mode

Finally, replace the content of src/App.jsx with the provided code. It imports and renders the ConverterForm component.

import ConverterForm from "./components/ConverterForm";

const App = () => {
  return (
    <div className="currency-converter">
      <h2 className="converter-title">Currency Converter</h2>
      <ConverterForm />
    </div>
  )
}

export default App;
Enter fullscreen mode Exit fullscreen mode

That’s it! If you’ve completed all the steps, you should now see your currency converter project in your browser. You can interact with it by entering an amount, selecting currencies, and clicking the swap button to switch between them.

Conclusion and final words

Building a currency converter with ReactJS and CSS is a rewarding project for beginners. It enhances your knowledge of React components, state management, and hooks, while also giving you hands-on experience with API integration and CSS styling.

Keep experimenting with additional features like historical exchange rates or different themes to continue learning and improving your skills. If you encounter any issues, you can download the source code files for free by clicking the “Download” button and view a live demo by clicking the “View Live” button.

After downloading the zip file, unzip it and open the “currency-converter” folder in VS Code. Then, open components/ConverterForm.jsx file and paste your API key into the API_KEY variable within the getExchangeRate() function. For security, consider storing your API key in a .env file in your project’s root directory. You can get a free API key from the ExchangeRate-API website.

Finally, open the terminal by pressing Ctrl + J and run these commands to view your currency converter project in the browser:

npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

View Live Demo

Download Code Files


If you’ve found my content helpful, please consider buying me a coffee to support me in creating more content.

Buy Me A Coffee

Top comments (0)