- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Articles
- How to pass an argument to the event handler in Tkinter?
- How do I add a simple onClick event handler to an HTML5 canvas element?
- How to add an event handler to an element in JavaScript HTML DOM?
- How to use Link Component in ReactJS?
- How to use Paper Component in ReactJS?
- How to add an event handler to the specified element in JavaScript?\n
- How to create Menu Item Component in ReactJS?
- How do I pass a variable to a MySQL script?
- ReactJS – Component vs PureComponent
- How to add or remove multiple classes to a ReactJS Component?
- How do I test a Python program or component?
- How to set Parent State from Children Component in ReactJS?
- HTML5 / JS storage event handler
- How do I pass environment variables to Docker containers?
- How do I catch a Ctrl+C event in C++?
