Event handlers in react js
Events are what make a webpage interactive. Anytime the user mouses over a part of the website, an event is created. The same is true for anything ranging from clicking on an image to typing in a text box or even the loading of the page. The origin of these events come from HTML and it's JavaScript's job to know how to listen for them and then handle them.
onChange event in Functional Component
onClick events in functional components
Event handlers are functions that get executed when a given event happens. For example, you can use them to send a message after the user clicks on a button.
You might already know event handlers from plain HTML and JavaScript. Event handlers in React are very similar. HTML provides us with event handlers like onclick
, onchange
, onfocus
, and many more. We can use them by adding them to the HTML element as an attribute.
onSubmit events in functional components
Form tag:
Note that the code to trigger the submission is attached to the form instead of the button.onSubmit
property in the form tag to run a function when the user press the form button.
event.preventDefault()
on theonSuscribe
function. This line is necessary to avoid the webpage to reload automatically after sending the form.Reloading the page was the normal behavior when you needed server-sided languages to do basic form manipulation before JavaScript became a powerful language.
Because the form is not directly connected to a state that changes the event, you can omit the arrow function to pass the event like in the input field.
Input tag:
- The input has a property
value
that receives the state.The input also has a propertyonChange
that runs an arrow function each time the user types inside the field. - The arrow function has 2
events
: - The input event fired each time the user types.
- The same event passed as an argument to be used in a function.import { useState } from "react";export default function App() {const [name, setName] = useState("");function onSuscribe(event) {event.preventDefault();alert(`Welcome on board ${name}`);}function onName(event) {setName(event.target.value);}return (<div className="App"><h1>Our new customer is {name}</h1><form onSubmit={onSuscribe}><input value={name} onChange={(event) => onName(event)} /><br /><button>Suscribe</button></form></div>);}
onChange - onSubmit Rjs:: Events