0

I am trying to implement a swipe feature in ReactJS, but before I even really dive in, I cannot seem to get the onTouchStart event listener to work. I have looked online but most answers are outdated, or do not address my question directly. This link is where I got the most information thus far, but it still falls short of my question and some of the answers are outdated. What's the proper way of binding touchstart on React JS?

I went down to creating the simplest form of the functionality and included that code below. I was trying to console.log when onTouchStart={this.swiped}> occurs. On a side note, if I change the listener to onClick onClick={this.swiped}>, this works immediately.

class App extends React.Component {
   contructor() {
    super();
    this.swiped = this.swiped.bind(this);
   }

  swiped() {
    console.log("Swiped")    
  }

  render() {
    return (
     <div>
      <div 
      className='swipe-card'
      onTouchStart={this.swiped}>Swipe Me
      </div>
    </div>
    )
  }
}

Also, I have added the CSS style cursor: pointer to the element. I also tried adding

componentWillMount: function(){
  React.initializeTouchEvents(true);
}

But according to the React blogs, React.initializeTouchEvents is no longer required.

This seems so trivial and something that should be really simple to implement. What am I missing? My goal is to implement this without an external library. Here is a link to Codepen where I was trying to implement this. https://codepen.io/jorgeh84/pen/mMdBZg

jorgehjr84
  • 11
  • 1
  • 1

2 Answers2

3

This works for me. Maybe the issue is that you're not testing it on a real device?

class App extends React.Component {
  contructor() {
    super();
  }

  swiped = () => {
    console.log("Swiped")    
  }

  render() {
    return (
      <div>
        <div className='swipe-card' onTouchStart={this.swiped}>Swipe Me</div>
      </div>
    )
  }
}


ReactDOM.render(<App />, document.getElementById('App'))
Daniel Andrei
  • 2,654
  • 15
  • 16
0

I realized that Daniel was onto something. So I do not need to be testing on an actual device, however, when using Chrome, you will need to use their device toolbar to simulate a mobile device for this to work.

jorgehjr84
  • 11
  • 1
  • 1