How do I pass an event handler to a component in ReactJS?


Reactjs is an open source javascript library, used in web development to build interactive pages in websites. Reactjs provides user friendly, declarative, and precise.

Components

Components are individualistic and reusable bits of code in react js. It helps to create separate files for our class and function. In general components are two types− class components and function components.

Event Handlers

Event handlers define what action to be performed when an event is fired or triggered. Events in react preceded with “on” for example onClick, and onFocus.

Event handler in react is just like DOM in HTML, react has also same handler − (click,mouse,and hover, etc).

Note  All events in react are named using camelCase and react handler should be written in curly braces.

To work with React, first of all, you need to import the library “react” using the following statement −

import React from "react"

Also import dom elements as −

import ReactDom from 'react-dom/client';

There are various types of event handlers they are −

  • Event handler

  • Inline event handler

  • Call back event handler

Passing (normal) Event handlers to components

First, we will start with onClick event handlers in react, it is the most basic example of how to operate events in react with event handlers. A button has onClick attributes which receive the function. This function is called every time an event is triggered.

Example 1

Following is an example of event handlers. In the UI we are creating a button named “click me” and we are linking the onClick event with the show() method.

Therefore, When you click the button the contents of this method will be executed. In this function, we are writing a code to display an alert message.

When you click on the button an “onClick” event will be triggered and this will show your Name.

<button onClick={show} > show is a function </button> import React from "react" import ReactDom from ‘react-dom/client’; function showName() { Const show = ()=>{ alert("your Name"); } return(<button onClick={show} >click me</button>); }; Const root = ReactDom.createRoot(document.getElementById(‘root’)); root.render(<showName /> )

Example 2

Let us another example here we are performing Increment and decrement operations to a number.

App.js

import './App.css'; import react,{useState} from "react"; function App() { const [count, setCount] = useState(0) // this function which computes the increment and decrement, initial value of count is 0 const inc = () => { setCount(count + 1); } const dec = () => { setCount(count - 1); } const handleChange = (e)=>{ setCount(e.target.value); } return ( <div className="App"> <button className='inc' type='button' onClick={inc}> + </button> <input type="text" value={count} onChange={handleChange}/> <button className='dec' type='button' onClick={dec}> - </button> </div> ); } export default App;

You can also add the following CSS code to this application. Save this with name App.css and import it in yor App.js as: import "./App.css";

In the following example, data type float is not supported if you pass float value as an argument then evaluation is false. isSafeInteger() method only supports the Integer value in their range otherwise it gives false.

.App{ display: flex; align-items: center; justify-content: center; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .inc{ background: green; color: red ; font-size: 20px; } .dec{ background: red; color: green; font-size: 20px; } input{ background-color: aquamarine; font-size: 20px; }

Passing Inline Event handlers to components

Inline event handlers is also called as inline handlers. It will pass in the htmls tags, inline event handlers are easy to pass and we no need to call separate functions.

Example

Following is an example of inline event handlers. We are calling two function through inline way. First is increasing the count second is decreasing the count.

<button onClick={show} > show is a function </button> import React from 'react'; function App() { const [count, setCount] = React.useState(0); return ( <div className="App"> Count: {count} <button type="button" onClick={() => setCount(count + 1)} > Increase Count </button> <button type="button" onClick={() => setCount(count - 1)} > Decrease Count </button> </div> ); } export default App;

You can also add the following CSS code to this App.css. and import it in yor App.js as: import "./App.css"; then it will looks like same as given output.

button{ background-color: green; color: aliceblue; padding: 10px; margin: 10px; border-radius: 5px; }

Passing Call back Event Handler to handlers

Last but not least, call back event handlers or call back handlers. They are in use when a child component needs to be communicated with parent components is known as call back event handlers.

Example

Following is an example of call back event handlers.

<button onClick={show} > show is a function </button> import React from 'react'; function App() { const [text, setText] = React.useState(''); function handleTextChange(event) { setText(event.target.value); } return ( <div className="App"> <div><MyInput inputValue={text} onInputChange={handleTextChange} /> {text} </div> </div> ); } function MyInput({ inputValue, onInputChange }) { return ( <input type="text" value={inputValue} onChange={onInputChange} /> ); } export default App;

Conclusion

React event handler is similar to html event handler only with some differences of syntax it is easy to use ‘this’ keyword is common in both. This is a JavaScript behavior not a react behavior. Reactjs is a JavaScript library. We have discussed event handling using ‘click’ but there are many other event handlers and all the above rules apply to them as well.

Updated on: 08-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements