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?
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.