Next.js & React-Currency-Format: A Beginner’s Guide

In the world of web development, handling currency can be a tricky business. From displaying prices in the correct format to ensuring user input is valid, there are many potential pitfalls. Imagine building an e-commerce website where prices are displayed incorrectly or, worse, where users can’t easily input monetary values. These seemingly small issues can lead to frustration for your users and, ultimately, lost sales. This tutorial will introduce you to react-currency-format, a powerful npm package that simplifies currency formatting and input in your Next.js applications.

Why React-Currency-Format?

react-currency-format is a React component that makes it easy to format currency values and handle currency input in a user-friendly way. It offers a variety of features, including:

  • Formatting: Automatically formats numbers as currency, including the correct symbols, decimal places, and thousands separators.
  • Input Handling: Provides a masked input field that guides users in entering currency values, preventing common errors.
  • Customization: Allows you to customize the formatting and input behavior to match your specific requirements.
  • Accessibility: Designed with accessibility in mind, ensuring a good user experience for everyone.

By using react-currency-format, you can significantly improve the user experience of your Next.js applications that deal with currency, making them more professional and user-friendly. Let’s dive in and see how it works.

Setting Up Your Next.js Project

Before we start, make sure you have a Next.js project set up. If you don’t, you can create one using the following command in your terminal:

npx create-next-app my-currency-app
cd my-currency-app

Once your project is created, navigate to your project directory. Now, let’s install the react-currency-format package:

npm install react-currency-format --save

This command downloads and installs the package and adds it to your project’s dependencies. With the package installed, we’re ready to start building our currency-formatted components.

Basic Currency Formatting

Let’s start with a simple example of displaying a currency value. We’ll modify the pages/index.js file.

Open pages/index.js and replace the existing content with the following code:

import CurrencyFormat from 'react-currency-format';

function HomePage() {
  const price = 1234.56;

  return (
    <div>
      <h1>Currency Formatting Example</h1>
      <p>Price: </p>
    </div>
  );
}

export default HomePage;

Let’s break down this code:

  • We import the CurrencyFormat component from the react-currency-format package.
  • We define a price variable with a numeric value.
  • We use the CurrencyFormat component to display the price.
  • The value prop is set to the price.
  • displayType={'text'} tells the component to render the formatted value as plain text.
  • thousandSeparator=',' specifies the character to use for separating thousands.
  • decimalSeparator='.' specifies the character to use for the decimal point.
  • prefix={'$ '} adds a dollar sign and a space before the value.

Save the file and start your Next.js development server using:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see the formatted price, which will appear as: $ 1,234.56. This simple example demonstrates how easy it is to format currency using react-currency-format.

Currency Input with Masking

Now, let’s look at how to use react-currency-format for currency input. This is where the masking feature comes in handy, guiding users to enter values correctly.

Modify your pages/index.js file again. Replace the previous content with the following code:

import CurrencyFormat from 'react-currency-format';
import { useState } from 'react';

function HomePage() {
  const [amount, setAmount] = useState('');

  const handleAmountChange = (values) => {
    const { value } = values;
    setAmount(value);
  };

  return (
    <div>
      <h1>Currency Input Example</h1>
      
      <p>Entered Amount: {amount}</p>
    </div>
  );
}

export default HomePage;

Let’s break down the new code:

  • We import the useState hook from React to manage the input value.
  • We initialize a state variable amount to an empty string.
  • We define a handleAmountChange function that updates the amount state whenever the input value changes. It receives an object with the value as a prop.
  • We use the CurrencyFormat component as an input field.
  • The value prop is bound to the amount state.
  • onValueChange is an event handler that is triggered when the input value changes. This prop receives an object with the value as a prop.
  • We add a CSS class currency-input for styling (we’ll add the CSS next).
  • We display the entered amount below the input field.

To style the input field, add the following CSS to your project. You can create a file like styles/globals.css (if you don’t already have one) and import it into pages/_app.js:

.currency-input {
  width: 200px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

In your pages/_app.js, import the CSS file:

import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return ;
}

export default MyApp;

Save all files and refresh your browser. You should now see an input field with the currency format. When you type in the field, the input will automatically format the numbers as currency, including the dollar sign, thousands separators, and decimal points. The entered amount will also be displayed below the input field.

Customizing the Currency Format

react-currency-format offers several options for customizing the currency format to match your specific needs. Let’s look at some of the most common customization options.

Changing the Currency Symbol

You can change the currency symbol using the prefix and suffix props. For example, to display the Euro symbol:


This will display the value as: € 1,234.56.

Changing the Decimal Places

You can control the number of decimal places using the decimalScale prop. For example, to display two decimal places:


This will display the value as: $ 1,234.50.

Allowing Negative Values

By default, react-currency-format does not allow negative values. You can enable negative values using the allowNegative prop:


This will display the value as: $ -123.45.

Using a Custom Input

Sometimes, you may want to use a custom input component. You can achieve this using the renderText and renderInput props. We will focus on the renderInput prop for this example. The renderInput prop allows you to customize the input element. Here’s an example:

import CurrencyFormat from 'react-currency-format';
import { useState } from 'react';

function HomePage() {
  const [amount, setAmount] = useState('');

  const handleAmountChange = (values) => {
    const { value } = values;
    setAmount(value);
  };

  return (
    <div>
      <h1>Currency Input Example</h1>
       }
      />
      <p>Entered Amount: {amount}</p>
    </div>
  );
}

export default HomePage;

In this example, we’re using the renderInput prop to render a custom input element with the class name custom-currency-input. You can then style this input using CSS.

.custom-currency-input {
  width: 200px;
  padding: 8px;
  border: 2px solid blue;
  border-radius: 6px;
  font-size: 18px;
}

This allows you to completely customize the appearance and behavior of the input field.

Common Mistakes and How to Fix Them

While react-currency-format is a powerful tool, it’s essential to be aware of common mistakes and how to avoid them.

Incorrect Prop Usage

Mistake: Using props incorrectly, such as passing a string to the value prop when a number is expected, or not using the correct event handler (onValueChange) for input fields.

Solution: Always refer to the documentation to understand the correct usage of each prop. Make sure you are passing the correct data types to the props.

Not Handling Input Changes Properly

Mistake: Not updating the state correctly when the input value changes, which can lead to unexpected behavior or errors.

Solution: Use the onValueChange event handler to update the state. Ensure that you are extracting the correct value from the event object (values.value).

Ignoring Accessibility

Mistake: Not considering accessibility when styling the input field, which can make it difficult for users with disabilities to interact with your application.

Solution: Ensure your input field has sufficient contrast, labels, and appropriate ARIA attributes. Test your application with screen readers to verify accessibility.

Best Practices for Using React-Currency-Format

To get the most out of react-currency-format, consider these best practices:

  • Use the correct props: Always refer to the documentation to use the right props for your use case.
  • Validate user input: While the package handles formatting and masking, you should still validate user input on the backend to ensure data integrity.
  • Provide clear labels: Always provide clear labels for your currency input fields.
  • Test thoroughly: Test your currency formatting and input fields with different currencies, decimal places, and input values to ensure they work as expected.
  • Consider internationalization (i18n): If you’re building an application for a global audience, consider using a library like react-intl to handle currency formatting and localization.

Summary / Key Takeaways

In this tutorial, we’ve explored how to use react-currency-format in your Next.js applications to handle currency formatting and input. We’ve covered the basics of displaying currency values, creating masked input fields, and customizing the format to meet your specific requirements. We’ve also addressed common mistakes and provided best practices to ensure you can implement this package effectively. By using react-currency-format, you can create more user-friendly and professional applications that handle currency with ease.

FAQ

Here are some frequently asked questions about react-currency-format:

  1. Can I use react-currency-format with other input validation libraries?

    Yes, you can integrate react-currency-format with other validation libraries. You might need to adjust your validation logic to account for the formatted values.

  2. How do I handle different currencies?

    While react-currency-format handles the formatting, you’ll need to manage the currency symbol and potentially the decimal and thousands separators based on the selected currency. You can use the `prefix` and `decimalSeparator` props to customize the display.

  3. Can I use react-currency-format in a form?

    Yes, you can use it in a form. Remember to handle the input value changes using the onValueChange prop and store the formatted value in your state. When submitting the form, you might need to parse the formatted value to get the actual number.

  4. How can I customize the input field’s appearance?

    You can customize the input field’s appearance using CSS. You can also use the renderInput prop to render a custom input element. This provides greater control over the appearance and behavior of the input field.

As you continue your journey in web development, remember that the details matter. Tools like react-currency-format are not just conveniences; they are essential components in crafting user-friendly applications. Properly formatted currency, easy-to-use input fields, and attention to detail contribute to a polished and professional user experience. By mastering these tools, you’ll be well-equipped to tackle the challenges of building robust and user-centric web applications.