React by Patrik

React Click Event Handlers

Event handlers determine what action is to be taken whenever an event is fired. This could be a button click or a change in a text input.

You would write this as follows in React:

function ActionLink() {
  const handleClick = (e) => {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <button onClick={handleClick}>Click me</button>
  );
}
...see more

Inline functions allow you to write code for event handling directly in JSX. See the example below:

import React from "react";

const App = () => {
  return (
    <button onClick={() => alert("Hello!")}>Say Hello</button>
  );
};

export default App;
...see more

Another common use case for event handlers is passing a parameter to a function in React so it can be used later. For example:

import React from "react";

const App = () => {
  const sayHello = (name) => {alert(`Hello, ${name}!`);
  };

  return (
    <button onClick={() => {sayHello("John");}}>Say Hello</button>
  );
};

export default App;

Comments

Leave a Comment

All fields are required. Your email address will not be published.