”;
In the previous chapters, we have learned that events are just some actions performed by a user to interact with any application. They can be the smallest of actions, like hovering a mouse pointer on an element that triggers a drop-down menu, resizing an application window, or dragging and dropping elements to upload them etc.
For each of these events, JavaScript provides responses. So, every time an event is performed by the user, it usually requires some type of reaction from the application; and these reactions are defined as some functions or blocks of code, called Event Handlers.
To understand event handling better, let us try to introduce events into an example application (Expense Manager APP). In this chapter we are trying to handle Mouse Events in the expense manager app. Mouse events are just some actions performed by users using mouse. These include hovering, clicking, dragging or simply any action that can be performed on an application using a mouse.
Handling Events in Expense Manager APP
Let us do some event management in our expense application. We can try to highlight the expense entry item in the table when the user moves the cursor over it.
Step 1 − Open expense-manager application in your favorite editor.
Open ExpenseEntryItemList.js file and add a method handleMouseEnter to handle the event fired (onMouseEnter) when the user moves the mouse pointer into the expense items (td – table cell).
handleMouseEnter(e) { e.target.parentNode.classList.add("highlight"); }
Here,
-
Event handler tries to find the parent node (tr) of the event target (td) node using parentNode method. The parentNode method is the standard DOM method to find the immediate parent the current node.
-
Once the parent node is found, event handler access the list of the css class attached to the parent node and adds ”highlight” class using add method. classList is the standard DOM property to get list of class attached to the node and it can be used to add / remove class from a DOM node.
Step 2 − Next, add a method, handleMouseLeave() to handle the event fired when the user moves out of the expense item.
handleMouseLeave(e) { e.target.parentNode.classList.remove("highlight"); }
Here, Event handler removes the highlight class from the DOM.
Add another method, handleMouseOver() to check where the mouse is currently positioned. It is optional to find the where about of the mouse pointer in the DOM.
handleMouseOver(e) { console.log("The mouse is at (" + e.clientX + ", " + e.clientY + ")"); }
Step 3 − Bind all event handlers in the constructor of the component.
this.handleMouseEnter = this.handleMouseEnter.bind(); this.handleMouseLeave = this.handleMouseLeave.bind(); this.handleMouseOver = this.handleMouseOver.bind();
Step 4 − Attach the event handlers to the corresponding tag in the render method.
render() { const lists = this.props.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> </tr> ); return ( <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> </tr> </thead> <tbody> {lists} </tbody> </table> ); }
The final and complete code of the ExpenseEntryItemList is as follows −
import React from ''react''; import ''./ExpenseEntryItemList.css''; class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); this.handleMouseEnter = this.handleMouseEnter.bind(); this.handleMouseLeave = this.handleMouseLeave.bind(); this.handleMouseOver = this.handleMouseOver.bind(); } handleMouseEnter(e) { e.target.parentNode.classList.add("highlight"); } handleMouseLeave(e) { e.target.parentNode.classList.remove("highlight"); } handleMouseOver(e) { console.log("The mouse is at (" + e.clientX + ", " + e.clientY + ")"); } render() { const lists = this.props.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> </tr> ); return ( <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> </tr> </thead> <tbody> {lists} </tbody> </table> ); } } export default ExpenseEntryItemList;
ExpenseEntryItemList.css:
Next, open the css file, ExpenseEntryItemList.css and add a css class, highlight.
tr.highlight td { background-color: #a6a8bd; }
index.js
Open index.js and use the ExpenseEntryItemList component.
import React from ''react''; import ReactDOM from ''react-dom''; import ExpenseEntryItemList from ''./components/ExpenseEntryItemList'' const items = [ { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" }, { id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" }, { id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" }, { id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" }, { id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" }, { id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" }, { id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" }, { id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" }, { id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" }, { id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" } ] ReactDOM.render( <React.StrictMode> <ExpenseEntryItemList items={items} /> </React.StrictMode>, document.getElementById(''root'') );
Serve the application using npm command.
npm start
Open the browser and enter http://localhost:3000 in the address bar and press enter.
The application will respond to mouse events and highlight the currently selected row.
Item | Amount | Date | Category |
Pizza | 80 | Sat Oct 10 2020 | Food |
Grape Juice | 30 | Man Oct 12 2020 | Food |
Cinema | 210 | Fri Oct 16 2020 | Entertainment |
Java Programming book | 242 | Thu Oct 15 2020 | Academic |
Mango Juice | 35 | Fri Oct 16 2020 | Food |
Dress | 2000 | Sun Oct 25 2020 | Cloth |
Tour | 2555 | Thu Oct 29 2020 | Entertainment |
Meals | 300 | Fri Oct 30 2020 | Food |
Mobile | 3500 | Mon Nov 02 2020 | Gadgets |
Exam Fees | 1245 | Wed Nov 04 2020 | Academic |
”;