In today’s interconnected world, dealing with multiple currencies is a common occurrence. Whether you’re traveling, managing international finances, or simply curious about exchange rates, a currency converter app can be incredibly useful. This tutorial will guide you through building a simple yet functional currency converter using React JS, a popular JavaScript library for building user interfaces. We’ll break down the process step-by-step, making it easy for beginners to understand and build their own app. By the end of this tutorial, you’ll have a working currency converter and a solid understanding of fundamental React concepts.
Why Build a Currency Converter?
Currency conversion is a practical problem with a straightforward solution, making it an excellent project for learning React. Here’s why building a currency converter is a great idea:
- Practical Application: You’ll create something you can actually use!
- Learn Core Concepts: You’ll work with state management, API calls, and component interactions – all essential React skills.
- Manageable Scope: It’s a small project, perfect for beginners, without being overly simplistic.
This tutorial will cover everything from setting up your React environment to fetching real-time exchange rates and displaying the converted amounts. Let’s dive in!
Prerequisites
Before we start, make sure you have the following:
- Node.js and npm (or yarn) installed: These are essential for managing JavaScript packages and running your React application. You can download them from nodejs.org.
- A basic understanding of HTML, CSS, and JavaScript: Familiarity with these technologies will help you understand the code.
- A code editor: VS Code, Sublime Text, or any editor of your choice.
Setting Up Your React Project
Let’s start by creating a new React project using Create React App, a popular tool that simplifies the setup process. Open your terminal and run the following command:
npx create-react-app currency-converter
cd currency-converter
This command creates a new directory called currency-converter, sets up all the necessary files, and installs the required dependencies. The cd currency-converter command navigates you into the project directory.
Now, start the development server by running:
npm start
This will open your app in your default web browser, usually at http://localhost:3000. You should see the default React app’s welcome screen. Now, let’s clean up the default files to make way for our currency converter.
Cleaning Up the Default Files
Open the project in your code editor. We’ll start by deleting or modifying the following files:
- src/App.js: This is the main component of your application. We’ll replace its content.
- src/App.css: This file contains the styles for the app. We’ll modify it as needed.
- src/index.css: We can keep this for global styles.
- src/index.js: We’ll keep this as is.
- src/App.test.js, src/logo.svg, src/reportWebVitals.js, src/setupTests.js: These files are not essential for our project, so you can delete them.
Now, let’s create the basic structure of our currency converter application.
Building the Currency Converter Components
We’ll create three main components:
- App.js: The main component that holds everything together.
- CurrencyInput.js: An input field for entering the amount to convert and selecting the currency.
- ExchangeRate.js: Displays the exchange rate for the selected currencies.
Creating the CurrencyInput Component
Create a new file named CurrencyInput.js inside the src directory. Add the following code:
import React from 'react';
function CurrencyInput({
amount,
currency,
currencies,
onAmountChange,
onCurrencyChange,
}) {
return (
<div>
onAmountChange(e.target.value)}
/>
onCurrencyChange(e.target.value)}>
{currencies.map((currencyCode) => (
{currencyCode}
))}
</div>
);
}
export default CurrencyInput;
This component takes several props:
- amount: The amount entered in the input field.
- currency: The selected currency code.
- currencies: An array of available currency codes.
- onAmountChange: A function to handle changes in the amount input.
- onCurrencyChange: A function to handle changes in the currency selection.
The component renders an input field for the amount and a select dropdown for the currency. The onChange events trigger the respective functions passed as props.
Creating the ExchangeRate Component
Create a new file named ExchangeRate.js inside the src directory. Add the following code:
import React from 'react';
function ExchangeRate({
fromCurrency,
toCurrency,
exchangeRate,
isLoading,
}) {
if (isLoading) {
return <p>Loading exchange rate...</p>;
}
if (!exchangeRate) {
return <p>Exchange rate not available.</p>;
}
return (
<p>
1 {fromCurrency} = {exchangeRate.toFixed(4)} {toCurrency}
</p>
);
}
export default ExchangeRate;
This component displays the exchange rate. It takes the following props:
- fromCurrency: The source currency code.
- toCurrency: The target currency code.
- exchangeRate: The exchange rate value.
- isLoading: A boolean indicating whether the exchange rate is being fetched.
The component handles loading and error states and displays the exchange rate formatted to four decimal places.
Building the App Component (App.js)
Now, let’s modify src/App.js to incorporate the other components and handle the core logic of the currency converter. Replace the content of src/App.js with the following code:
import React, { useState, useEffect } from 'react';
import CurrencyInput from './CurrencyInput';
import ExchangeRate from './ExchangeRate';
import './App.css'; // Import the CSS file
const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key
const BASE_URL = 'https://api.exchangerate-api.com/v4/latest';
function App() {
const [amount1, setAmount1] = useState(1);
const [amount2, setAmount2] = useState(1);
const [currency1, setCurrency1] = useState('USD');
const [currency2, setCurrency2] = useState('EUR');
const [exchangeRate, setExchangeRate] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [currencies, setCurrencies] = useState([]);
useEffect(() => {
const fetchCurrencies = async () => {
try {
const response = await fetch(`${BASE_URL}`);
const data = await response.json();
setCurrencies(Object.keys(data.rates)); // Extract currency codes
} catch (error) {
console.error('Error fetching currencies:', error);
}
};
fetchCurrencies();
}, []);
useEffect(() => {
const fetchExchangeRate = async () => {
setIsLoading(true);
try {
const response = await fetch(
`${BASE_URL}?base=${currency1}&symbols=${currency2}`
);
const data = await response.json();
const rate = data.rates[currency2];
setExchangeRate(rate);
} catch (error) {
console.error('Error fetching exchange rate:', error);
setExchangeRate(null);
} finally {
setIsLoading(false);
}
};
fetchExchangeRate();
}, [currency1, currency2]);
useEffect(() => {
if (exchangeRate) {
setAmount2((amount1 * exchangeRate).toFixed(2));
}
}, [amount1, exchangeRate]);
function handleAmount1Change(amount) {
setAmount1(amount);
if (exchangeRate) {
setAmount2((amount * exchangeRate).toFixed(2));
}
}
function handleCurrency1Change(currency) {
setCurrency1(currency);
}
function handleCurrency2Change(currency) {
setCurrency2(currency);
}
return (
<div>
<h1>Currency Converter</h1>
setAmount2(amount)}
onCurrencyChange={handleCurrency2Change}
/>
</div>
);
}
export default App;
This is the main component that orchestrates the entire application. Let’s break down the code:
- Import Statements: Import the necessary modules and components.
- State Variables:
amount1, amount2: Stores the amounts in the two currency input fields.currency1, currency2: Stores the selected currency codes.exchangeRate: Stores the exchange rate.isLoading: A boolean to indicate loading state.currencies: An array to store available currencies.
- useEffect Hooks:
- Fetching Currencies: An effect to fetch the list of available currencies from the API when the component mounts.
- Fetching Exchange Rate: An effect to fetch the exchange rate whenever the selected currencies change.
- Updating Amount2: An effect to update the second amount whenever the first amount or the exchange rate changes.
- Event Handlers: Functions to handle changes in the amount and currency selections.
- JSX Structure: Renders the
CurrencyInputcomponents and theExchangeRatecomponent, passing the necessary props.
Styling the App (App.css)
Create a new file named App.css inside the src directory. Add the following CSS styles to make the app visually appealing:
.app {
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
font-family: sans-serif;
}
h1 {
margin-bottom: 20px;
}
.currency-input {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.currency-input input {
width: 100px;
padding: 5px;
margin-right: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.currency-input select {
padding: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
This CSS provides basic styling for the app’s layout, input fields, and select dropdown.
Fetching Exchange Rates from an API
To get real-time exchange rates, we’ll use a free and open exchange rate API. There are many options available. For this tutorial, we will use the ExchangeRate-API. First, you need to sign up for an API key. Once you have your API key, replace 'YOUR_API_KEY' in the App.js file with your actual API key.
The code in App.js already includes the necessary logic to fetch exchange rates. Here’s a summary:
- API Endpoint: We use the
https://api.exchangerate-api.com/v4/latestendpoint. - Fetching Exchange Rates: The
useEffecthook with dependencies oncurrency1andcurrency2is used to fetch the exchange rate whenever the selected currencies change. - Error Handling: The code includes error handling using
try...catchblocks to manage potential API request failures. - Loading State: The
isLoadingstate variable is used to indicate when the exchange rate is being fetched.
Running and Testing Your App
Now that you’ve built the components and implemented the logic, it’s time to run your app and test it. Save all the files and go back to your terminal. Make sure you are in the project directory (currency-converter) and run the following command:
npm start
This command will start the development server and open your app in your default web browser. You should see two currency input fields and the exchange rate displayed below. You can now:
- Enter an amount in the first input field.
- Select different currencies from the dropdowns.
- See the converted amount and the exchange rate update in real-time.
Common Mistakes and How to Fix Them
Here are some common mistakes beginners make when building React applications and how to fix them:
- Incorrect import paths: Double-check that your import paths are correct. Make sure you are importing components from the correct files.
- Unnecessary re-renders: Use the
React.memooruseMemohook to prevent unnecessary re-renders of components. - State updates not working: Ensure you are using the correct
set...functions to update state variables. - API key issues: Verify that you’ve correctly entered your API key and that it’s valid.
- CORS errors: If you encounter CORS (Cross-Origin Resource Sharing) errors, ensure your API supports CORS or use a proxy server.
- Incorrect dependency array in useEffect: Make sure you include all the necessary dependencies in the
useEffecthook’s dependency array to avoid unexpected behavior.
Key Takeaways
Let’s recap what we’ve learned:
- Component-Based Architecture: React applications are built using components. We created
CurrencyInput, andExchangeRatecomponents. - State Management: We used the
useStatehook to manage the app’s state. - API Calls: We used the
fetchAPI to fetch exchange rates from an external API. - Event Handling: We used the
onChangeevent to handle user input and update the state. - Conditional Rendering: We used conditional rendering to display different content based on the loading state.
FAQ
- How can I add more currencies?
To add more currencies, you need to fetch the available currencies from the API and add them to the
currenciesstate variable. Ensure your API supports the currencies you want to add. - How can I handle errors more gracefully?
You can improve error handling by displaying more informative error messages to the user and logging errors to the console. Implement try…catch blocks to handle API errors and other potential issues.
- How can I improve the app’s performance?
To improve performance, consider optimizing your API calls, using memoization techniques, and minimizing unnecessary re-renders. Also, make sure to use production build for deployment.
- How can I add user input validation?
You can add user input validation by using libraries like Formik or implementing custom validation logic within the
onChangehandlers of the input fields. Validate the input before updating the state.
Building this currency converter has given you a practical understanding of React fundamentals. You’ve learned how to structure a React application, manage state, fetch data from an API, and create reusable components. The skills you’ve gained here are transferable to many other React projects. You can now build more complex applications by combining these fundamental concepts with additional libraries and features. With the basics in place, you can experiment with different UI designs, add more features, and explore the vast possibilities that React offers. The world of front-end development is constantly evolving, and by continuing to practice and experiment, you’ll be well-equipped to build amazing applications.
