2
I need to create a component for evaluation, where it is possible to evaluate something with 0-5 stars by clicking on the star icons.
But the way I do it, I’m exceeding the amount of this.setState()
nested, which causes error as it can cause an infinite loop.
Component Code:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { Container } from './styles';
class StarsToRate extends Component {
constructor(props) {
super(props)
const {
size,
} = this.props;
this.state = {
rating: 0,
iconSize: size,
}
}
render() {
const { rating, iconSize } = this.state;
return (
<Container>
{[1, 2, 3, 4, 5].map((element) => {
if (element <= rating) {
return <Icon name="star" size={iconSize} color="#EBC600" onPress={this.setState({ rating: element })} />;
}
return <Icon name="star-border" size={iconSize} color="#EBC600" onPress={this.setState({ rating: element })} />;
})}
</Container>
);
}
}
StarsToRate.defaultProps = {
size: 24,
};
StarsToRate.propTypes = {
size: PropTypes.number,
};
export default StarsToRate;
Error displayed:
The problem is not that you’re calling the
setState
always? Tries to change theonPress
for:onPress={element => this.setState({rating: element})}
– Felipe Avelar
element
used in the Arrow Function is already stated in the upper scope, using in this way accuses an error. I tried to bypass calling another functiontouchStar(data) {
 this.setState({ rating: data });
 }
, but back to setState’s mistake nested.– Maurício Soares