Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6213

combine states for a rating component

$
0
0

I am trying to make a star rating component. I am using ternary operators to check if a state is true or not. If yes, I use a yellow star or else a white one. However, this looks like bad code practice. Instead of repeating all these ternary operators, is it possible to somehow combine the conditions and render only those yellow stars whose state is true?

const [oneStar, setOneStar] = useState(false);const [twoStar, setTwoStar] = useState(false);const [threeStar, setThreeStar] = useState(false);const [fourStar, setFourStar] = useState(false);const [fiveStar, setFiveStar] = useState(false);const ratings = [    1,2,3,4,5]const setRating = (rating: number) => {  console.log('rating', rating);  if(rating == 1){      setOneStar(true);      setTwoStar(false);      setThreeStar(false);      setFourStar(false);      setFiveStar(false);  }  if(rating == 2){    setOneStar(true);    setTwoStar(true);    setThreeStar(false);    setFourStar(false);    setFiveStar(false);}if(rating == 3){    setOneStar(true);    setTwoStar(true);    setThreeStar(true);    setFourStar(false);    setFiveStar(false);}if(rating == 4){    setOneStar(true);    setTwoStar(true);    setThreeStar(true);    setFourStar(true);    setFiveStar(false);}if(rating == 5){    setOneStar(true);    setTwoStar(true);    setThreeStar(true);    setFourStar(true);    setFiveStar(true);}};return (<View style={styles.ratingContainer}><TouchableOpacity onPress={() => setRating(1)}>        {oneStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(2)}>        {twoStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(3)}>        {threeStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(4)}>        {fourStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity><TouchableOpacity onPress={() => setRating(5)}>        {fiveStar ? <Icon name= "star" color='#ebba34' size={moderateScale(13)} /> : <Icon name= "star-o" size={moderateScale(13)} />}</TouchableOpacity></View>);};

Viewing all articles
Browse latest Browse all 6213

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>