React: Passing Parameters to Event Handler Functions

Updated: March 3, 2023 By: A Goodman Post a comment

React supports a lot of events and the names that you can hardly not know are onClick, onChange, onSubmit, onReset, onContextMenu, onDrag, onMouseOver, etc.

This article shows you how to pass parameters to an event handler function in modern React. We are going to walk through 2 examples. The first one is written in Javascript and the second one comes with TypeScript. The similarity is that they both use functional components instead of class-based components. Therefore, this and bind() are not going to appear.

Example 1: Using Javascript

Preview

This example uses a function named onClickHandler to handle the onClick event coming from one of the two buttons (Button 1 and Button 2). We will pass the name of the button into the handler function to show which button was clicked.

The code

1. Create a new React project by running:

npx create-react-app example

2. Remove all of the default code in your src/App.js and add the following:

// App.js
// Kindacode.com

import { useState } from "react";
import "./App.css";

const App = () => {
  const [text, setText] = useState("No button was clicked");

  const onClickHandler = (event, source) => {
    // Do something with event
    console.log(event);

    // Use the passed parameter
    setText(`${source} has been clicked`);
  };

  return (
    <>
      <div className="container">
        <button onClick={(event) => onClickHandler(event, "Button 1")}>
          Button 1
        </button>

        <button onClick={(event) => onClickHandler(event, "Button 2")}>
          Button 2
        </button>

        <h2>{text}</h2>
      </div>
    </>
  );
};

export default App;

3. (This step is optional) Replace the default code in App.css with the below:

.container {
  width: 500px;
  margin: 50px auto;
  text-align: center;
}

button {
  margin: 0px 20px;
  padding: 15px 30px;
  border: none;
  cursor: pointer;
  background: purple;
  color: white;
  font-weight: bold;
}

button:hover {
  background: red;
}

Example 2: Using TypeScript

In this example, we will handle 3 events that are very common when working with forms: onSubmit, onChange, and onClick.

Preview

When each event handler function is triggered, you will see the parameter passed in the console.

The Code

1. Create a new React project by performing the command below:

npx create-react-app example_2 --template typescript

2. Clear the default code in your App.tsx and add this:

// App.tsx
// Kindacode.com

import React, { useState } from "react";
import "./App.css";

const App = () => {
  const [inputValue, setInputValue] = useState('');

  const onSubmitHandler = (
    event: React.FormEvent<HTMLFormElement>,
    param: string
  ) => {
    event.preventDefault();

    // Do something with passed parameter
    console.log(param);
  };

  const onChangeHandler = (
    event: React.ChangeEvent<HTMLInputElement>,
    param: string
  ) => {
    setInputValue(event.target.value);

    // Do something with passed parameter
    console.log(param);
  };

  const onClickHandler = (
    event: React.MouseEvent<HTMLButtonElement>,
    param: string
  ) => {
    // Do something with passed parameter
    console.log(param);
  };

  return (
    <div className="container">
      <form onSubmit={(e) => onSubmitHandler(e, "Form onSubmit param")}>
        <input
          type="text"
          onChange={(e) => onChangeHandler(e, "This is input onChange param")}
          placeholder="Search..."
          value={inputValue}
        />
        <button
          type="submit"
          onClick={(e) => onClickHandler(e, "This is button onClick param")}
        >
          Search
        </button>
      </form>
    </div>
  );
};

export default App;

3. Some CSS to make our app look a little bit more beautiful:

/* 
App.css
Kindacode.com
 */

.container {
  padding: 50px;
  display: flex;
  justify-content: space-between;
}

Conclusion

We’ve explored how to pass arguments to an event handler function. This technique is quite useful in many scenarios when you are developing React projects with Javascript or TypeScript. If you would like to learn more about modern frontend development, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles