How to create dynamic components in React Native?

Asked

Viewed 505 times

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:

inserir a descrição da imagem aqui

  • The problem is not that you’re calling the setState always? Tries to change the onPress for: onPress={element => this.setState({rating: element})}

  • 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 function touchStar(data) {&#xA; this.setState({ rating: data });&#xA; }, but back to setState’s mistake nested.

1 answer

1


The problem is that you are calling the function as soon as you create the component. Try to replace in the components the:

onPress={this.setState({ rating: element })}

for:

onPress={() => this.setState({ rating: element })}

Functional example with buttons

Browser other questions tagged

You are not signed in. Login or sign up in order to post.