Home > front end >  How do i hide the currency symbol when there is no input?
How do i hide the currency symbol when there is no input?

Time:09-23

So i am making a create product page. The items were product name, product price, product description. There are gonna be times where user doesnt want to input any price on their product just yet. In that case i dont want it to show currency with the value 0 on the page. Is there any way to hide the currency? thank you

const [price, setPrice] = useState();

  const formatter = new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
  });

<p className="card-text">{formatter.format(item.price)}</p>

CodePudding user response:

You can add a condition to check the empty value of item.price on your JSX like below

<p className="card-text">{Boolean(item.price) && formatter.format(item.price)}</p>

If you want to reuse that formatter for other values, I'd suggest you introduce a function

const formatCurrency = (priceValue) => {
   if(!priceValue) {
     return '';
   }

   return new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
  });
}

<p className="card-text">{formatCurrency(item.price)}</p>
  • Related