|6. Event Handling in React
Chapter 6React Tutorial~1 min read

Event Handling in React

Events — User Interactions Handle करणे

Event म्हणजे user ने केलेली action — button click, input type, form submit. React मध्ये events handle करायला camelCase prop names वापरतात — onClick, onChange, onSubmit.

onClick — button click

jsx
import { useState } from 'react';

function ClickExample() {
  const [message, setMessage] = useState("Click करा!");

  // Named handler function
  function handleClick() {
    setMessage("Button click झाला! 🎉");
  }

  return (
    <div>
      <p>{message}</p>

      {/* Named function reference — () नाही! */}
      <button onClick={handleClick}>Click Me</button>

      {/* Inline arrow function */}
      <button onClick={() => setMessage("Inline click!")}>
        Inline Click
      </button>

      {/* Args pass करायला arrow function वापरतात */}
      <button onClick={() => handleGreet("Rahul")}>
        Greet Rahul
      </button>
    </div>
  );
}

onChange — Input Events

Controlled input — form handling

jsx
import { useState } from 'react';

function LoginForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  function handleSubmit(e) {
    e.preventDefault();  // page reload थांबवतो
    alert(`Login: ${email}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}  // e.target.value = typed text
        placeholder="Email टाका"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password टाका"
      />
      <button type="submit">Login</button>
    </form>
  );
}

Common Events

  • onClick — button, div, span click
  • onChange — input, textarea, select value बदलणे
  • onSubmit — form submit होणे
  • onKeyDown / onKeyUp — keyboard press
  • onMouseEnter / onMouseLeave — hover effects
  • onFocus / onBlur — input focus/unfocus
💡

onClick={handleClick} — function reference द्यायचे. onClick={handleClick()} — चुकीचे! () लावले तर component render होताना लगेच call होतो, click वर नाही.

Key Points — लक्षात ठेवा

  • onClick, onChange, onSubmit — camelCase event props
  • e.preventDefault() — form चे default behavior थांबवतो
  • e.target.value — input मध्ये typed value
  • onClick={fn} — reference, onClick={fn()} — immediately calls!
  • Args pass करायला: onClick={() => fn(arg)}
0/12 chapters पूर्ण