Components for formatting text

Instead of formatting text by calling helper functions inside render, we can create a separate component that
handles this.

With Component

Render function is lot cleaner to comprehend as it is just simple component composition.

  1. const Price = (props) => {
  2. // toLocaleString is not React specific syntax - it is a native JavaScript function used fo formatting
  3. // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
  4. const price = props.children.toLocaleString('en', {
  5. style: props.showSymbol ? 'currency' : undefined,
  6. currency: props.showSymbol ? 'USD' : undefined,
  7. maximumFractionDigits: props.showDecimals ? 2 : 0
  8. });
  9. return <span className={props.className}>{price}</span>
  10. };
  11. Price.propTypes = {
  12. className: PropTypes.string,
  13. children: PropTypes.number,
  14. showDecimals: PropTypes.bool,
  15. showSymbol: PropTypes.bool
  16. };
  17. Price.defaultProps = {
  18. children: 0,
  19. showDecimals: true,
  20. showSymbol: true,
  21. };
  22. const Page = () => {
  23. const lambPrice = 1234.567;
  24. const jetPrice = 999999.99;
  25. const bootPrice = 34.567;
  26. return (
  27. <div>
  28. <p>One lamb is <Price className="expensive">{lambPrice}</Price></p>
  29. <p>One jet is <Price showDecimals={false}>{jetPrice}</Price></p>
  30. <p>Those gumboots will set ya back
  31. <Price
  32. showDecimals={false}
  33. showSymbol={false}>
  34. {bootPrice}
  35. </Price>
  36. bucks.
  37. </p>
  38. </div>
  39. );
  40. };

Without Component

Less code: But render looks less clean. (Debatable, yeah I understand)

  1. function numberToPrice(num, options = {}) {
  2. const showSymbol = options.showSymbol !== false;
  3. const showDecimals = options.showDecimals !== false;
  4. return num.toLocaleString('en', {
  5. style: showSymbol ? 'currency' : undefined,
  6. currency: showSymbol ? 'USD' : undefined,
  7. maximumFractionDigits: showDecimals ? 2 : 0
  8. });
  9. }
  10. const Page = () => {
  11. const lambPrice = 1234.567;
  12. const jetPrice = 999999.99;
  13. const bootPrice = 34.567;
  14. return (
  15. <div>
  16. <p>One lamb is <span className="expensive">{numberToPrice(lambPrice)}</span></p>
  17. <p>One jet is {numberToPrice(jetPrice, { showDecimals: false })}</p>
  18. <p>Those gumboots will set ya back
  19. {numberToPrice(bootPrice, { showDecimals: false, showSymbol: false })}
  20. bucks.</p>
  21. </div>
  22. );
  23. };

Reference: