Cleaner way to pass a prop with conditions

Viewed 42

I have a component that accepts props like this:

   <Description
    priceValue={
      product.price && isOutlet
        ? product.price_outlet === '0'
          ? ''
          : `${product.price_outlet}`
        : `${product.price}`
    }
    />

I would like to not put all this condition inside the priceValue prop.

My solution is:

 const PriceBox = () => {
          return product.price && isOutlet
            ? product.price_outlet === '0'
              ? ''
              : `${product.price_outlet} ${product.currencySymbol}`
            : `${product.price} ${product.currencySymbol}`;
        };

   <Description priceValue={<PriceBox/>}/>

Can anyone tip me if there is a cleaner way to achieve it?

Thanks in advance

2 Answers

You could extract the logic into a variable before the render:

const priceValue = (
  product.price && isOutlet
    ? (product.price_outlet === '0'
      ? ''
      : `${product.price_outlet}`)
    : `${product.price}`
);

return (
  <Description priceValue={priceValue} />
);

Or, if you prefer, to a function:

const getPriceValue = () => (
  product.price && isOutlet
    ? (product.price_outlet === '0'
      ? ''
      : `${product.price_outlet}`)
    : `${product.price}`
);

return (
  <Description priceValue={getPriceValue()} />
);

The function may be preferred if the context of this is within something like a map() operation, where product might be different for each element. For example:

const getPriceValue = (product) => (
  product.price && isOutlet
    ? (product.price_outlet === '0'
      ? ''
      : `${product.price_outlet}`)
    : `${product.price}`
);

return (
  <>
    {products.map(product => (
      <Description priceValue={getPriceValue(product)} />
    ))}
  </>
);

One method is to assign it to a variable, and then pass it in as props.

For example:

const priceValue = product.price && isOutlet ? product.price_outlet === '0' ? '' : product.price_outlet: product.price

Alternatively, you could use easier to read if statements:

let priceValue;

if (product.price && isOutlet) {
    if (product.price_outlet === '0') {
        priceValue = ""
    } else {
        priceValue = product.price_outlet
    }
} else {
    priceValue = product.price
}

After either of these solutions, you could then just pass the Description component props of priceValue={priceValue}. This will make viewing what you are returning much easier to read.

Related