2

I want to refactor my following code to display multiple icons, using a loop. I have tried looking for examples but so far I have found map being used on arrays, but I don't have array or any collection.

<View style={{ flexDirection: 'row', alignItems: 'center' }}> <Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} /> <Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} /> <Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} /> <Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} /> <Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} /> </View> 

screenshot

1
  • I rather would use react-native-star-rating package, which handles that for you, also it covers halve stars. Commented Jun 20, 2019 at 13:37

2 Answers 2

4

You can use a function which returns an array of Icon tags to render these stars,Check following code segment.

export default class App extends React.Component { createStars = () => { let stars = [] for (let i = 0; i < 5; i++) { stars.push(<Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} />) } return stars } render() { return ( <View style={styles.container}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> {this.createStars()} </View> </View> ); } } 
Sign up to request clarification or add additional context in comments.

Comments

2

Split it into small functions

const renderIcon = () => <Icon type="FontAwesome" name="star" style={{ fontSize: 30, color: '#f1c40f' }} />; const renderIcons = num => [...Array(num)].map(renderIcon); <View style={{ flexDirection: 'row', alignItems: 'center' }}> {renderIcons(5)} {renderIcons(4)} {renderIcons(3)} {renderIcons(2)} {renderIcons(1)} </View> 

You can take it further and add name style to renderIcon

4 Comments

This answer seems definitely cool, but you can also use Array(num).fill(num) instead of [...Array(num)], giving you more options.
@CarlosAbraham Thank you, but whats the options it gives us ?
[...Array(3)] creates an empty array of size 3, with undefined values in it, you can do Array(3) and it would be the same thing. It is just another option, I wanted to share :)
@CarlosAbraham Ah my bad, I thought you meant it give us more options in renderIcons woops, Thanks for sharing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.