2
\$\begingroup\$

I've written this Card component which is composed of thumbnail image, name, symbol, total_volume, current_price, and price_change_percentage_24h.

enter image description here

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?

asked May 12, 2021 at 2:38
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

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

answered May 12, 2021 at 4:14
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.