How to use JavaScript class to create utility function in React JS
I was searching ways to better organise code in React application and I found it is good to use classes in creating utility functions.
Here is a program example
Utility functions
class FormattingUtils {
static formatCurrency(amount, currency) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount);
}
static formatPercentage(value, decimals = 2) {
return `${(value * 100).toFixed(decimals)}%`;
}
}
export default FormattingUtils;
Usage in Component
import React from 'react';
import FormattingUtils from './FormattingUtils';
function Product(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Price: {FormattingUtils.formatCurrency(props.price, props.currency)}</p>
<p>Discount: {FormattingUtils.formatPercentage(props.discount)}</p>
</div>
);
}
export default Product;
In this example, the FormattingUtils
class defines two static methods: formatCurrency()
and formatPercentage()
. These methods use the Intl.NumberFormat
and Number.toFixed()
methods to format numbers as currency or percentages.
These methods simplify the code and make it easier to maintain, since the formatting logic is contained in a separate utility class.
By using a class to define utility functions, you can take advantage of the benefits of object-oriented programming, such as encapsulation, abstraction, and inheritance. You can also extend and customize the functionality of the utility class by creating subclasses or overriding its methods.