I've written this Card component which is composed of thumbnail image
, name
, symbol
, total_volume
, current_price
, and price_change_percentage_24h
.
I want to refactor my renderPriceChange
function since it's using the same pattern.
const renderPriceChange = (price) => {
if (price > 0) {
return (
<Text style={styles.rise}>
<AntDesign name='caretup' color='#03AE9D' size={10} />{' '}
{percentageFormat(item.price_change_percentage_24h)}%
</Text>
);
} else {
return (
<Text style={styles.drop}>
<AntDesign name='caretdown' color='#fb2c33' size={10} />{' '}
{percentageFormat(item.price_change_percentage_24h)}%
</Text>
);
}
};
How to make it look cleaner with smart and less code?
1 Answer 1
It is equivalent to:
const renderPriceChange = (price) => {
return (
<Text style={price > 0 ? styles.rise : styles.drop}>
<AntDesign
name={price > 0 ? 'caretup' : 'caretdown'}
color={price > 0 ? '#03AE9D' : '#fb2c33'}
size={10}
/>{' '}
{percentageFormat(item.price_change_percentage_24h)}%
</Text>
)
}
You can inline the if...else
by using JavaScript's ternary operator a ? b : c
Explore related questions
See similar questions with these tags.