Tuesday, May 5, 2020

React 16.4 Pointer Events example

Pointer events were introduces in React 16.4 to handle mouse and touch events. In jQuery we have only mouse events, now with the introduction of touch screen and devices like iPad we need to handle touch events also. React now introduces pointer events which can handle both mouse and touch events.

In the below example we will capture 2 Pointer events onPointerEnter & onPointerLeave. We will add these events to a DIV, when we move the mouse over the DIV or touch the DIV the onPointerEnter event will trigger in the event handlers we toggle the isHover state property which will in turn change the color of the DIV. By default the DIV gets silver color, when we hover the mouse over the DIV or touch the DIV its color will change to golden color.
import React from 'react';

class App extends React.Component {
  state = {
    isHover: false
  }

  onEnter = (e) => {
    this.setState({isHover: true});
  }
  onLeave = (e) => {
    this.setState({isHover: false});
  }

  render() {
    const {isHover} = this.state;

    const myStyle = {
      width: '100px',
      height: '100px',
      backgroundColor: isHover ? 'gold' : 'silver'
    };

    return (
      <div className="App">
        <header className="App-header">
          <div onPointerEnter={this.onEnter}
               onPointerLeave={this.onLeave} style={myStyle}>
          </div>
        </header>
      </div>
    );
  };
}

export default App;


Search Flipkart Products:
Flipkart.com

No comments: