R
Rishtaara
React: The Complete Guide
Lesson 8 of 28Article16 min

Events & Conditionals

React events use camelCase names: onClick, onChange, onSubmit. Pass a function — not a string like HTML onclick.

React Events — onClick, onChange, onSubmit

React events use camelCase names: onClick, onChange, onSubmit. Pass a function — not a string like HTML onclick.

The event object is a SyntheticEvent — similar to the browser event but works the same across browsers.

Real-life example: React events are like a reception desk bell. You do not shout instructions (inline strings); you register who handles the ring (a function).

Click and change handlers
function LikeButton() {
  function handleClick() {
    alert("Thanks for liking Rishtaara!");
  }

  return <button onClick={handleClick}>Like</button>;
}

function SearchBox() {
  function handleChange(event) {
    console.log("Typing:", event.target.value);
  }

  return <input type="text" onChange={handleChange} placeholder="Search courses" />;
}

Prevent default and stop propagation

Call event.preventDefault() on form submit to stop page reload. Call event.stopPropagation() when a child click should not bubble to parent.

Real-life example: preventDefault is telling the post office not to redirect your letter to a new address — you handle it locally in JavaScript.

Form submit without reload
function LoginForm() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log("Form handled in React — no page reload");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" placeholder="Email" />
      <button type="submit">Log in</button>
    </form>
  );
}

Conditionals — showing UI based on state

Use ternary (? :), logical &&, or if/else before return to show different UI for different conditions.

Real-life example: Conditionals are like a shop sign — "Open" when the owner is inside, "Closed" when they are away.

Conditional rendering patterns
function Dashboard({ isLoggedIn, error, items }) {
  if (!isLoggedIn) {
    return <p>Please log in to see your Rishtaara dashboard.</p>;
  }

  return (
    <div>
      {error && <p className="error">{error}</p>}
      {items.length === 0 ? (
        <p>No courses yet — start learning!</p>
      ) : (
        <ul>{items.map((item) => <li key={item.id}>{item.title}</li>)}</ul>
      )}
    </div>
  );
}