←Nested Component and Composition Model - part 6
In our earlier lessons, we learned about reuse and data passing using variables or props, but everything was static—we learned how to define data, pass it, and then render it—and react isn't just about creating static applications.
We need dynamic elements where users can interact with our application, so in this chapter, we'll start moving in that direction. By adding event handlers, we'll learn how to interact with users.
But first, let me refresh you about how events work in vanilla JavaScript before we move on to explain events in react.
Events are actions that take place as a result of user interaction, such as clicking a button, waiting for a webpage to load, changing an input field, and so forth.
There are many helpful events, including Mouse events, Keyboard events, Form events, Document events, and CSS events.
In addition, we assign a handler on events that execute JavaScript code or functions when user interaction occurs. Go ahead and visit JavaScript.info/events for more information.
It is similar but more straightforward to handling events in React, but with some syntax differences. When using events in React, there are some guidelines we should follow.
Event Naming in React
The handler can be assigned using HTML-attribute or, in React, JSX-attribute 'on<event>'. For instance, we can use "onClick" to specify the click event for a button.
However, because HTML-attribute names are case-insensitive, they are lowercase in standard JavaScript or we can also use names like onClick, onCLICK, or ONCLICK instead.
But when naming events in React, we should always use camelCase verbs like onClick or onSubmit.
We define an event handler as an element's value in JSX and use it to make elements react to user input. In React, we never pass the handler as a string because using single or double quotes inside of events will cause them to fail. Instead, we give the handler as a JavaScript expression or a function in JSX.
Let's apply an event to the button, we already have in our demonstration application.
<button onClick={() => alert("New List Created")}>Add List</button>
Here we are writing an inline function for event handling directly in JSX but it is inconvenient to write code in JSX because it is less readable and harder to maintain; we create a function and pass the function name as the value of events. When passing in JSX, keep in mind that parenthesis should not be used after the function name.
const MyComponent = () => {
const handleClick = () => {
alert('New List is Created')
}
return <button className={className} onClick={handleClick}>Add List </button>
}
Although you are free to add however you like, it is a common practice to create the function name in this way: add a handle, followed by the name of the event, in this case, "handleClick".
Arguments Passed to Event Handlers
The majority of the time, we pass a parameter to an event handler. In JSX, we can use either the arrow function or the simple function to pass an argument to an event handler.
const MyComponent = () => {
const handleClick = (name) => {
alert(`${name} added in list`);
}
return <button className={className} onClick={() => handleClick('Joe')}>Add List </button>
}
Default Behavior in React
Numerous events carried out particular actions automatically, such as submitting a form, selecting the text, and navigating. Sometimes, in certain situations, we don't want these actions to take place in the browser; instead, we want to implement some other behavior, such as checking to see if all of the fields are filled before the user submits the form, and so forth.
In React, the third difference is that in order to avoid default behavior in React, we must explicitly call preventDefault() because passing 'return false' as we do in HTML will not work here.
const MyComponent = () => {
const handleLink = (e) => {
e.preventDefault();
}
return <a href="https://reactjs.org/docs/handling-events.html" onClick={handleLink}>Handling Events </a>
}
Event objects in react
When something occurs in the browser, such as when we click a button, we automatically receive an event object that contains all the information necessary to describe what happened and pass it as an argument to the event handler.
In React, we also get the object 'e', a synthetic event. An event object is passed as the first argument whenever the handler is assigned or the function is passed. The information about what happened is contained in that object.
Here, using event.type to get the event type or use target—which identifies the DOM elements. Let's see how We can get the button value by using e.target.value.
const handleClick = (e) => {
alert(e.target.value);
}
<button value="Create New List" onClick= {handleClick}>Add List</button>
Let's use another example since React supports more events. In the example below, we'll use onDoubleClick. When we click the text twice, an alert will show up on the screen as a result of the DoubleClick event.
<h5 onDoubleClick={handleDoubleClick}>Hello World!</h5>
const handleDoubleClick = (e) => {
alert('I am heading')
}
Pass events handler as a prop to a function component
React events always bubble; you can pass the event handler to the nested component as a prop, and the event will be captured when you click the nested element.
const App = () => {
return <MyComponent onClick={handleClick}>
}
const MyComponent = (props) => {
return <button onClick= {props.onClick}>Add List</button>
}
As you can see, we treat event props similarly to how we treat regular props. Additionally, you can pass the onClick attribute directly in the curly braces as an argument rather than using the props keyword.
Conclusion
This article explains the event handler by using the example of the onClick event in React and its uses. With a few extension changes, events in React behave similarly to how they do in the DOM. We use events in React as a JSX attribute with the on keyword and event names that begin with a capital letter, such as onClick and onFocus.
In React, we don't have to specify the event listener; for instance, onClick automatically adds the click event listener to the button.
The function should be the value of events; to run code, we can pass the arrow function or use the function keywords in JSX directly.
Events in React can trigger state changes. This will be covered in our upcoming article.
0 Comments:
Post a Comment