My purpose is to render 5 stars in a line:

constructor(props) {
    super(props);
    this.state = {
        selectedStar: '',
        ...
    };

    this.starsArray = [1, 2, 3, 4, 5] // is used like indexes
}

onStarPress = (index) => {
    console.warn('index = ' + index); // index here is [object Object] instead of 1, 2, 3 ...
    this.setState({
        selectedStar: index
    });
}

renderStars = () => (
    this.starsArray.map((starIndex, i) => (
        <Star
            key = {i}
            color = {this.defineStarColor(starIndex)}
            onStarPress = {(starIndex) => {this.onStarPress(starIndex)}}
        />
    ))
)

When I do map() to the array of indexes starIndex is equal to [object Object] instead of 1, 2, 3 ...

i here does equal to 1, 2 ... as the key. But when I pass it to the functions below it also becomes [object Object]

What I'm doing incorrectly?

2 Answers

0
Slawomir Chodnicki On

Not sure how Star invokes your function, but if it's just using the given function as an event handler, then you are receiving the event object as your first argument. Hence, it's an object.

If you want it to pass on the index, have the Star component handle the DOM event, and call your supplied function with the expected arguments.

0
Community On

In this line onStarPress = {(starIndex) => {this.onStarPress(starIndex)}}, the first starIndex is event handling object. So onStarPress is receiving an object.

There are two ways to solve this:

onStarPress = (e,index) => {
    console.warn('e = ' + e); 
    console.warn('index = ' + index); 
    this.setState({
        selectedStar: index
    });
}

renderStars = () => (
    this.starsArray.map((starIndex, i) => (
        <Star
            key={i}
            color={this.defineStarColor(starIndex)}
            onStarPress={(e) => { this.onStarPress(e,starIndex) }}
        />
    ))
)

Other way is:

onStarPress = (index) => (e) => {
    console.warn('e = ' + e); 
    console.warn('index = ' + index); 
    this.setState({
        selectedStar: index
    });
}

renderStars = () => (
    this.starsArray.map((starIndex, i) => (
        <Star
            key={i}
            color={this.defineStarColor(starIndex)}
            onStarPress={this.onStarPress(starIndex)}
        />
    ))
)