Event Handling
Event handling in React components is crucial for defining the user interface's response to user interactions, such as clicking a button or submitting a form.
In usual HTML, we use the onclick
attribute of the button element to specify a function that handles the click event. React is similar, except the attribute name is in camelCase: onClick
.
In functional components, the functions that handle events are usually created as inline functions inside the component's function.
Following is a very simple example of event handling:
function Main(props) {let handleClick = (e) => {e.target.innerHTML = "Clicked!";};return (<button onClick={handleClick}>Click Me!</button>);}
In the above code, handleClick
is the inline function that sets the innerHTML
of the button to Clicked!
when it's clicked.
It is important to note that we can use an external function to handle events as well:
function handleClick(e) {e.target.innerHTML = "Clicked!";}function Main(props) {return (<button onClick={handleClick}>Click Me!</button>);}
However, the common convention is to use inline functions due to some of their advantages and neatness. Since inline functions have a local scope, we don't have to worry about duplicate naming.
Apart from that, accessing component data from the inline functions is easier, especially while using hooks which we will explore in the later chapters.
We can also directly embed inline functions into expressions to make the code shorter:
<button onClick={(e) => e.target.innerHTML = "Clicked!"}>Click Me!</button>
We can also pass extra arguments to event handlers using the following method:
function handleClick(e, text) {e.target.innerHTML = text;}function Main(props) {return (<button onClick={(e) => handleClick(e, 'An Extra Argument!')}>Click Me!</button>);}
Thanks for your feedback!