Event Handling in React

Event Handling in React

ยท

2 min read

Event Handling is almost the same in React and vanilla JavaScript.But before understanding about EventHandles we need to learn about React Props.

Reading Props in React

What is Prop?

Prop is the short form for Properties & refers to the data that is passed down from a parent component to a child component. Props are used to customize the behavior and appearance of a component, and they can be accessed inside the component using the props object.

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}
function App() {
  return (
    <div>
      <Greeting name="Rahul" />
      <Greeting name="RB" />
    </div>
  );
}

JavaScript vs React

Add Event Listeners :

In vanilla JavaScript, we typically add event listeners to elements using the addEventListener method. But in React, we can add event listeners to elements by passing a function as a prop.

here is the Example

const button = document.getElementById('myButton');
button.addEventListener('click', function() {
  // Do something when the button is clicked
});

In React, you would add a onClick prop to the button element. Simple.

function handleClick() {
  // Do something when the button is clicked
}
function MyButton() {
  return (
    <button onClick={handleClick}>Click me</button>
  );
}

๐Ÿ“Œ Note :

In React Functions passed to event handlers must be passed, not called.

For example:

passing a function (correct)calling a function (incorrect)
<button onClick={handleClick}><button onClick={handleClick()}>

In the First Example, the handleClick function is passed as an onClick event handler & This tells React to remember it and only call your function when the user clicks the button.

โ“โ“why Calling () a function is not working here as Vanilla JS

Because if you call an event handler instead of passing it (Triggered when the event happens) then React takes it as a normal prop and fires immediately during rendering.

Conclusion

React make event handling very handy as we don't need to do that boring

document.getElementById('btn').addEventListner('click',()) . we can easily handle events with the help of JSX(For HTML) and props.

By: Rahul Bisht

Please Like it and if there are areas of improvement, please comment.

ย