Currency Converter

Build a small interface to convert amounts from one currency to another using a static exchange rate.

Solution

Current Rate: GBP to USD 1.25

GBP Amount

USD Amount

0

Explanation

Using React useRef and useState efficiently

useRef enables you to reference the value entered by the user to retrieve the current value. While useState is used for the update to keep track of the value and ensure that the output gets updated when the user enters a new value.

Tips

When using forms, ensure that you prevent the default behaviour to submit the data and rerender the page.

Creating better user experience

Note that if the user doesn't enter a value and presses the submit button, then 0 is entered to prevent errors.

Without TypeScript, the browser will still parse this with JavaScript fine most likely. However, defensive coding, parsing and using optional chaining, ensures you will consistently get the results you expect.

Code

import { useRef, useState } from "react";
import styles from "./Solution.module.css";

const Solution = () => {
  const conversionRate_GBP_to_USD: number = 1.25;
  const inputAmount = useRef<HTMLInputElement>(null);
  const [usdAmount, setUsdAmount] = useState<number>(0);

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const gbp: number = parseInt(inputAmount?.current?.value || "0");
    setUsdAmount(gbp * conversionRate_GBP_to_USD);
  };

  return (
    <div>
      <div>
        Current Rate: GBP to USD <span>{conversionRate_GBP_to_USD}</span>
      </div>
      <br />
      <form onSubmit={handleSubmit}>
        <div>GBP Amount</div>
        <input className={styles.inputAmount} type="text" ref={inputAmount} />
        <input className={styles.inputSubmit} type="submit" value="Convert" />
      </form>
      <br />
      <div>USD Amount</div>
      <p>{usdAmount}</p>
    </div>
  );
};

export default Solution;

Styling

.inputAmount,
.inputSubmit {
  padding: 5px;
  margin-right: 5px;
}

Links