I want to add events listeners onTouchStart, Move and End to img tag in array.map function, as a result its catch only one event listener(onTouchStart), but if I set this listeners to div with class="header-added-heroes" all 3 listeners work, I read about binding 'this' to array.map and its catch only onTouchStart, I would be grateful for any information on this question.
{this.props.addedHeroes.map( function(el) {
return (<a name={el.link} key={uniqueId()} className="heroes__link">
<div className="hero"> {console.log(' map this : ', this === that)}
{
<img className="hero__image"
onTouchStart={this.onTouchStart}
onTouchMove={this.handleMove}
onTouchEnd={this.onTouchEnd}
src={el.image}
/>
}
</div>
</a>);
}, this )}
full code:
import React from "react";
import uniqueId from "lodash/uniqueId";
import HeroCounter from "../../images/HeroCounter.svg";
class HeaderAddedHeroes extends React.Component {
state = {
heroes: [1, 2, 3, 4],
showCloseButton: 0
};
constructor(props) {
super(props);
this.onTouchStart = this.onTouchStart.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
this.handleMove = this.handleMove.bind(this);
}
handleMove() {
console.log('moved');
this.setState({ showCloseButton: 1 })
}
onTouchStart() {
console.log('started');
this.setState({ showCloseButton: 2 })
}
onTouchEnd() {
console.log('ended');
this.setState({ showCloseButton: 3 })
}
render() { var that = this;
return (
<header className="header-added-heroes"> { console.log(' this : ', that)}
<div className="header-added-heroes"
onTouchMove={this.handleMove}
onTouchStart={ this.onTouchStart }
onTouchEnd={this.onTouchEnd}>
{ this.state.showCloseButton }
</div>
<div className="heroes">
{this.props.addedHeroes.map( function(el) {
return (<a name={el.link} key={uniqueId()} className="heroes__link">
<div className="hero"> {console.log(' map this : ', this === that)}
{
<img className="hero__image"
onTouchStart={this.onTouchStart}
onTouchMove={this.handleMove}
onTouchEnd={this.onTouchEnd}
src={el.image}
/>
}
</div>
</a>);
}, this )}
</header>
);
}
}
you can always use arrow function.
Solution was: to remove ‘uniqueId()’
{this.props.addedHeroes.map((el, i) => {
return (<a name={el.link} key={i} className="heroes__link">
<div className="hero">
<img className="hero__image"
onTouchStart={this.onTouchStart}
onTouchMove={this.handleMove}
onTouchEnd={this.onTouchEnd}
src={el.image}
/>
</div>
</a>);
}
)}