Nearby lessons

9 of 44

⚡ ReactJS – Events & Event Handling

📌 What are Events?

Events are actions or occurrences that happen in the system (e.g., a mouse click, a key press). React allows us to handle these events in a declarative way, similar to HTML, but with a few differences.

📌 What is an Event?

  • Events are actions or occurrences in the system.
  • They allow code to respond when something happens.
  • Most often, events are generated by the user of a website.

⚛️ React Events

  • React can perform actions based on user events just like HTML DOM events.
  • React has the same events as HTML: click, change, mouseover, etc.

🔑 Adding Events in React

There are some key differences when adding events in React:

  • React events are written in camelCase (e.g., onClick instead of onclick).
  • Event handlers are written inside curly braces {} (e.g., onClick={shoot}).
React Playground
import React from 'react'

const App = () => {
    function HelloFunction(){
        alert("Hello Brothers");
    }

  return (
    <div>
      <input type='button' value="Click" onClick={HelloFunction}/>
    </div>
  )
}

export default App

📦 Passing Arguments to Event Handlers

You can pass arguments to event handlers using an arrow function.

React Playground
import React from 'react'

const App = () => {
   const HelloFunction = (name) => {
    alert("Hello " + name);
   }

  return (
    <div>
      <input type='button' value="Click" onClick={() => HelloFunction("Rajesh")}/>
    </div>
  )
}

export default App

📥 Passing Props to Event Handlers

You can also pass arguments using props when rendering a component.

React Playground
import React from 'react'

const App = (props) => {
   const HelloFunction = (name) => {
    alert("Hello " + name);
   }

  return (
    <div>
      <input type='button' value="Click" onClick={() => HelloFunction(props.name)}/>
    </div>
  )
}

export default App

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - Conditional Rendering