Categories
React Projects

Create a Currency Converter with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a currency converter with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app currency-converter

with NPM to create our React project.

Create the Currency Converter

To create the currency converter, we write:

import React, { useMemo, useState } from "react";

export default function App() {
  const [value, setValue] = useState(0);
  const [fromCurrency, setFromCurrency] = useState("");
  const [toCurrency, setToCurrency] = useState("");
  const [currencies] = useState(["EUR", "USD", "CAD"]);
  const [result, setResult] = useState(0);

  const fromCurrencies = useMemo(() => {
    return currencies.filter((c) => c !== toCurrency);
  }, [currencies, toCurrency]);

  const toCurrencies = useMemo(() => {
    return currencies.filter((c) => c !== fromCurrency);
  }, [currencies, fromCurrency]);

  const convert = async (e) => {
    e.preventDefault();
    const formValid = +value >= 0 && fromCurrency && toCurrency;
    if (!formValid) {
      return;
    }
    const res = await fetch(
      `https://api.exchangeratesapi.io/latest?base=${fromCurrency}`
    );
    const { rates } = await res.json();
    setResult(+value * rates[toCurrency]);
  };

  return (
    <div>
      <form onSubmit={convert}>
        <div>
          <label>value</label>
          <input value={value} onChange={(e) => setValue(e.target.value)} />
        </div>
        <div>
          <label>from currency</label>
          <select
            value={fromCurrency}
            onChange={(e) => setFromCurrency(e.target.value)}
          >
            {fromCurrencies.map((c) => (
              <option key={c}>{c}</option>
            ))}
          </select>
        </div>
        <div>
          <label>to currency</label>
          <select
            value={toCurrency}
            onChange={(e) => setToCurrency(e.target.value)}
          >
            {toCurrencies.map((c) => (
              <option key={c}>{c}</option>
            ))}
          </select>
        </div>
        <button type="submit">convert</button>
      </form>
      <div>
        {value} {fromCurrency} is {result.toFixed(2)} {toCurrency}
      </div>
    </div>
  );
}

We have the value state that stores the value of the currency value to convert from.

fromCurrency has the currency to convert from.

toCurrency has the currency to convert to,

currencies has the currency choices.

result has the converted result.

fromCurrencies has the choices we can choose to convert from.

We use the useMemo hook with a callback to return all the currencies that we can pick from.

We exclude the toCurrency value from the returned array.

The 2nd argument has the values to watch in order for the first callback to run again to update the returned value.

Likewise, we do the same to define toCurrencies but we exclude the fromCurrency value instead.

Next, we define the convert function that does the currency conversion.

Inside it, we call e.preventDefault() to let us do client-side form submission.

Then we check if value is bigger than 0 and fromCurrency and toCurrency are set.

If all the conditions are met, we get the exchange rate from the Exchange Rate API.

Then we call setResult to compute converted currency value.

Next, we add the form to let us enter the values.

It has the onSubmit prop set to the convert function, which is run when we click on the button that has the type submit .

In it, it has an input to set the value .

e.target.value has the inputted value.

onChange is run whenever we change the entered value.

Likewise, we have the select dropdowns that lets us choose the currencies to convert from and to respectively.

We set their values as we did with the input with the value and onChange props.

We render the fromCurrencies and toCurrencies inside the select element to render the choices.

Below the form, we show the result to the user.

The toFixed method returns the string form of the number with the number of decimal places we pass in.

Conclusion

We can create a currency converter with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *