How to format currency in React JS App. Create Utility functions in React app for formating the currency data for shopping cart apps etc.
Inside src
folder create folder names utilities
utilities/formatCurrency.ts
const CURRENCY_FORMATTER = new Intl.NumberFormat(undefined, { currency: "USD", style: "currency" }) export const formatCurrency = (number: number) => { return CURRENCY_FORMATTER.format(number) }
undefined is given as the locale, so it automatically determines how to print out the number based on where you live.
components/StoreItem.tsx
import { Card } from "react-bootstrap" import { formatCurrency } from "../utilities/formatCurrency" type StoreItemProps = { id:number, name:string, price: number, imgUrl: string } const StoreItem = ({id, name, price, imgUrl} : StoreItemProps) => { return ( <Card> <Card.Img variant="top" src={imgUrl} height="200px" style={{ objectFit: "cover"}} /> <Card.Body className="d-flex flex-column"> <Card.Title className="d-flex justify-content-between align-items-baseline mb-4"> <span className="fs-2">{name}</span> <span className="ms-2 text-muted">{formatCurrency(price)}</span> </Card.Title> </Card.Body> </Card> ) } export default StoreItem
data/items.json
[ { "id": 1, "name": "Book", "price": 10.99, "imgUrl": "/imgs/book.jpg" }, { "id": 2, "name": "Computer", "price": 1199, "imgUrl": "/imgs/computer.jpg" }, { "id": 3, "name": "Banana", "price": 1.05, "imgUrl": "/imgs/banana.jpg" }, { "id": 4, "name": "Car", "price": 14000, "imgUrl": "/imgs/car.jpg" } ]
pages/Store.js
import { Col, Row } from "react-bootstrap"; import StoreItem from "../components/StoreItem"; import storeItems from "../data/items.json" const Store = () => { return <> <h1>Store</h1> <Row> { storeItems.map( item => ( <Col> <StoreItem {...item} /> </Col> )) } </Row> </>; }; export default Store;
This is how easily we can format currency in our react app using intl number format for currency. We can format based on USD, INR, AUD, etc.