Logo


User interaction in React js


The browser is an event-driven application. Everything that a user does in the browser fires an event, from clicking buttons to even just moving the mouse. In plain JavaScript, we can listen for these events and attach a JavaScript function to interact with them. For instance, we can attach a function to the mousemove browser event with the JS:



1const ele = document.getElementById('mousemove');
2ele.innerHTML = 'Move your mouse over this text';
3ele.addEventListener('mousemove', function(evt) {
4 const { screenX, screenY } = evt;
5 ele.innerHTML = '<div>Mouse is at: X: ' +
6 screenX + ', Y: ' + screenY +
7 '</div>';
8})

In React, however we don't have to interact with the browser's event loop in raw JavaScript as React provides a way for us to handle events using props . For instance, to listen for the mousemove event from the (rather unimpressive) demo above in React, we'll set the prop onMouseMove (notice the camelcasing of the event name).

1class MouseMover extends React.Component {
2 state = {
3 x: 0,
4 y: 0
5 };
6 handleMouseMove = e => {
7 this.setState({
8 x: e.clientX,
9 y: e.clientY
10 });
11 };
12 render() {
13 return (
14 <div onMouseMove={this.handleMouseMove}>
15 {this.state.x || this.state.y
16 ? "The mouse is at x: " + this.state.x + ", y: " +
17this.state.y
18 : "Move the mouse over this box"}
19 </div>
20 );
21 }
22} 

React provides a lot of props we can set to listen for different browser events, such as click, touch, drag, scroll, selection events, and many more.


About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share