How to Manage Events in React
Event handlers are functions that will be triggered in response to interactions like clicking, hovering, focusing form inputs, and so on.
const App = () => {
const handleClick = () => {
console.log('Clicked')
}
return <Button onClick={handleClick}>Click me!</Button>
}
Steps to adding an event.
- Write a function which handles the effect after handling event. Commonly event handlers are written as
handle
plus event name e.g. forclick
event it is written ashandleClick
, If it is change then it can be written ashandleChange
.
const handleClick = () => { console.log('clicked!!');}
- We can attach this handler to the interactive element like Button, Input, etc. Make sure you are writing this as below, do not write it like
onClick={handleClick()}
<Button onClick={handleClick} />
It also passes an event object with the event.
const handleClick = (e) => { console.log(e.target.value);}
We can also write this as inline function as below
<Button onClick={(e) => {console.log(e.target.value)}}
Q.: What are different common events?
...