Build a Simple Next.js Interactive Currency Converter

Written by

in

In today’s interconnected world, dealing with multiple currencies is commonplace. Whether you’re traveling, managing international finances, or simply curious about exchange rates, a currency converter is an incredibly useful tool. Building one yourself, especially with a framework like Next.js, offers a fantastic opportunity to learn modern web development practices and gain a practical skill. This article will guide you through creating a simple, yet functional, currency converter using Next.js, suitable for beginners and intermediate developers alike.

Why Build a Currency Converter with Next.js?

Next.js is a powerful React framework that offers several advantages for web development. It allows for server-side rendering (SSR) and static site generation (SSG), which can significantly improve performance and SEO. Moreover, Next.js provides features like built-in routing, API routes, and easy integration with external services. Building a currency converter with Next.js is a great way to:

  • Learn fundamental Next.js concepts: You’ll get hands-on experience with components, state management, API routes, and data fetching.
  • Create a practical application: A currency converter is a genuinely useful tool that you can use daily.
  • Improve your understanding of APIs: You’ll learn how to fetch data from an external currency exchange rate API.
  • Enhance your front-end development skills: You’ll practice building user interfaces (UI) with React and styling them with CSS.

Prerequisites

Before we begin, ensure you have the following:

  • Node.js and npm (or yarn): You’ll need these to install Next.js and manage project dependencies. Download and install them from the official Node.js website.
  • A code editor: Choose your preferred code editor (e.g., VS Code, Sublime Text, Atom).
  • Basic understanding of HTML, CSS, and JavaScript: Familiarity with these languages is essential for understanding the code and making modifications.

Step-by-Step Guide to Building the Currency Converter

1. Setting Up the Next.js Project

Let’s start by creating a new Next.js project. Open your terminal and run the following command:

npx create-next-app currency-converter
cd currency-converter

This command creates a new Next.js project named “currency-converter” and navigates you into the project directory. You can replace “currency-converter” with your preferred project name.

2. Installing Dependencies

For our currency converter, we’ll need a library to make API requests. We’ll use axios, a popular promise-based HTTP client. Install it by running:

npm install axios

3. Project Structure and File Setup

Your project directory should look something like this:


currency-converter/
├── node_modules/
├── pages/
│   └── index.js
├── public/
├── .gitignore
├── next.config.js
├── package-lock.json
├── package.json
└── README.md

We’ll be working primarily in the pages/ directory. The index.js file will be our main component, the landing page of our currency converter. We’ll create a few more components later to keep our code organized.

4. Creating the User Interface (UI)

Open pages/index.js and replace the default content with the following code. This sets up the basic UI structure, including input fields for the amount and currency selection, and a display area for the converted amount.


import { useState } from 'react';

export default function Home() {
  const [amount, setAmount] = useState('');
  const [fromCurrency, setFromCurrency] = useState('USD');
  const [toCurrency, setToCurrency] = useState('EUR');
  const [convertedAmount, setConvertedAmount] = useState(null);
  const [error, setError] = useState(null);

  return (
    <div style={{ fontFamily: 'sans-serif', padding: '20px' }}>
      <h1>Currency Converter</h1>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      <div style={{ marginBottom: '10px' }}>
        <label htmlFor="amount">Amount:</label>
        <input
          type="number"
          id="amount"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          style={{ marginLeft: '5px', padding: '5px', border: '1px solid #ccc', borderRadius: '4px' }}
        />
      </div>
      <div style={{ marginBottom: '10px', display: 'flex', alignItems: 'center' }}>
        <label htmlFor="fromCurrency" style={{ marginRight: '5px' }}>From:</label>
        <select
          id="fromCurrency"
          value={fromCurrency}
          onChange={(e) => setFromCurrency(e.target.value)}
          style={{ padding: '5px', border: '1px solid #ccc', borderRadius: '4px' }}
        >
          <option value="USD">USD</option>
          <option value="EUR">EUR</option>
          <option value="GBP">GBP</option>
          <option value="JPY">JPY</option>
          <option value="CAD">CAD</option>
          <!-- Add more currencies as needed -->
        </select>
      </div>
      <div style={{ marginBottom: '10px', display: 'flex', alignItems: 'center' }}>
        <label htmlFor="toCurrency" style={{ marginRight: '5px' }}>To:</label>
        <select
          id="toCurrency"
          value={toCurrency}
          onChange={(e) => setToCurrency(e.target.value)}
          style={{ padding: '5px', border: '1px solid #ccc', borderRadius: '4px' }}
        >
          <option value="EUR">EUR</option>
          <option value="USD">USD</option>
          <option value="GBP">GBP</option>
          <option value="JPY">JPY</option>
          <option value="CAD">CAD</option>
          <!-- Add more currencies as needed -->
        </select>
      </div>
      <button
        onClick={handleConvert}
        style={{ padding: '10px 20px', backgroundColor: '#4CAF50', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}
      >
        Convert
      </button>
      <div style={{ marginTop: '20px' }}>
        {convertedAmount !== null && (
          <p>{amount} {fromCurrency} = {convertedAmount.toFixed(2)} {toCurrency}</p>
        )}
      </div>
    </div>
  );
}

This code defines a React component with the following elements:

  • State variables: amount, fromCurrency, toCurrency, and convertedAmount to store the user input and the converted value. error to display error messages.
  • Input fields and select dropdowns: For entering the amount and selecting the currencies.
  • A “Convert” button: To trigger the currency conversion logic.
  • Display area: To show the converted amount.

We’ve also added some basic inline styles to make the UI look presentable. You can, of course, add more styling using CSS or a CSS-in-JS solution like styled-components if you prefer.

5. Fetching Exchange Rates from an API

To convert currencies, we need to fetch exchange rates from an external API. There are several free and paid currency APIs available. For this tutorial, we’ll use a free API like ExchangeRate-API. Sign up for a free API key (if required by the API you choose). Then, create a function to fetch the exchange rate using axios. Add the following code inside the Home component, just before the `return` statement:


  async function fetchExchangeRate() {
    if (!amount || isNaN(amount)) {
      setError('Please enter a valid amount.');
      setConvertedAmount(null);
      return;
    }

    setError(null);
    try {
      const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key
      const url = `https://v6.exchangerate-api.com/v6/${apiKey}/pair/${fromCurrency}/${toCurrency}/${amount}`;
      const response = await axios.get(url);

      if (response.data.result !== 'success') {
        setError('Error fetching exchange rate.');
        setConvertedAmount(null);
        return;
      }

      setConvertedAmount(response.data.conversion_result);
    } catch (error) {
      setError('An error occurred. Please try again later.');
      setConvertedAmount(null);
    }
  }

Important: Replace 'YOUR_API_KEY' with your actual API key from the ExchangeRate-API (or your chosen API). This function does the following:

  • Validates the input: Checks if the amount is valid.
  • Constructs the API URL: Uses template literals to build the API request URL, including the API key, currencies, and amount.
  • Makes the API request: Uses axios.get() to fetch the exchange rate data.
  • Handles the response: Checks the API response for success and updates the convertedAmount state accordingly. Also handles errors and sets the error state.

6. Implementing the Conversion Logic

Now, let’s connect the UI to the API. Add the following function inside the Home component, just after the fetchExchangeRate function:


  async function handleConvert() {
    await fetchExchangeRate();
  }

This function calls the fetchExchangeRate function when the “Convert” button is clicked. Now, add the `handleConvert` function to the `onClick` event of the button in the UI (in the `index.js` file):


        <button
          onClick={handleConvert}
          style={{ padding: '10px 20px', backgroundColor: '#4CAF50', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}
        >
          Convert
        </button>

Now, when the user clicks the “Convert” button, the handleConvert function is executed, which in turn calls the fetchExchangeRate function to fetch the exchange rate and update the UI with the converted amount.

7. Running the Application

To run your Next.js application, open your terminal, navigate to your project directory (currency-converter), and run the following command:

npm run dev

This command starts the development server. Open your web browser and go to http://localhost:3000 to see your currency converter in action. You should now be able to enter an amount, select currencies, and convert the amount.

Styling and Enhancements

The currency converter currently has basic styling. Here are some suggestions for enhancing its appearance and functionality:

  • Improve the UI: Use CSS, a CSS framework (like Bootstrap or Tailwind CSS), or a component library (like Material UI or Ant Design) to create a more visually appealing and user-friendly interface.
  • Add more currencies: Expand the currency selection options.
  • Implement error handling: Display more informative error messages to the user.
  • Add a loading indicator: Show a loading spinner while the API request is in progress.
  • Implement caching: Cache the exchange rates to reduce API calls and improve performance. Use useSWR or useContext to manage the caching.
  • Add a history feature: Store the conversion history in local storage.
  • Make it responsive: Ensure the application looks good on different screen sizes.

Common Mistakes and How to Fix Them

Here are some common mistakes and how to avoid them:

  • Incorrect API key: Ensure you’ve entered your API key correctly. Double-check your API key and verify that it is active.
  • CORS errors: If you’re encountering CORS (Cross-Origin Resource Sharing) errors, you may need to configure your API or use a proxy. A proxy can be set up using a Next.js API route.
  • Incorrect API URL: Make sure the API URL is correct and that you’re using the correct parameters. Check the API documentation.
  • Uncaught errors: Always wrap your API calls in try...catch blocks to handle potential errors gracefully. Log the errors to the console or use a logging service to help with debugging.
  • Ignoring input validation: Always validate user inputs to prevent unexpected behavior and errors.

Key Takeaways

  • Next.js is a powerful framework for building web applications.
  • You can easily integrate external APIs to fetch data.
  • State management is crucial for creating interactive applications.
  • Error handling is essential for a robust application.
  • Always validate user inputs to prevent errors.

FAQ

1. Where can I find a free currency API?

Several free currency APIs are available, such as ExchangeRate-API. Always check the API’s terms of service and usage limits before using it in a production environment.

2. How can I handle CORS errors?

If you encounter CORS errors, you can use a proxy server or create a Next.js API route to make the API request from your server instead of the client-side. The API route acts as an intermediary, avoiding the CORS restrictions.

3. How can I improve the performance of my currency converter?

To improve performance, consider caching the exchange rates, using server-side rendering (SSR) or static site generation (SSG), and optimizing your images and code. Use tools like Lighthouse to audit your website’s performance.

4. How do I add more currencies to the dropdowns?

Simply add more <option> elements to the <select> dropdowns in your UI, specifying the currency codes and display names.

5. Can I deploy this application?

Yes, you can deploy your Next.js application to platforms like Vercel, Netlify, or AWS. Vercel is especially well-suited for Next.js applications, offering seamless deployment and hosting.

Building a currency converter with Next.js is a rewarding learning experience that combines front-end development, API integration, and state management. By following the steps outlined in this article, you can create a functional and useful application while strengthening your skills in web development. Remember to experiment with different features, styling options, and API integrations to further enhance your project and expand your knowledge. The world of web development is constantly evolving, so embrace the opportunity to learn and build something that you can be proud of. Happy coding!