Categories
React Answers

How to Pass a Value to the onClick Callback in a React Component?

Spread the love

Sometimes, we want to pass a value to the onClick callback in our React component.

In this article, we’ll look at how to pass a value to the onClick callback in our React component.

Pass a Value to the onClick Callback in a React Component

One way to pass a value to the onClick callback is to pass in a function that calls another function into the onClick prop.

For instance, we can write:

import React from "react";

export default function App() {
  const onClick = (val) => {
    console.log(val);
  };

  return (
    <div className="App">
      <button onClick={() => onClick("clicked")}>click me</button>
    </div>
  );
}

We pass in:

() => onClick("clicked")

as the value of onClick .

This will run the onClick function when we click the button with 'value' passed in.

And we see that logged when we click on the button.

This will create a new function on every render.

A more efficient way to achieve the same result would be to create a function outside the onClick prop and pass it in.

To do this, we write:

import React from "react";

export default function App() {
  const onClick = (val) => (e) => {
    console.log(val);
  };

  return (
    <div className="App">
      <button onClick={onClick("clicked")}>click me</button>
    </div>
  );
}

We change the onClick function to take the val value and return a function with the click handler that logs val .

And then we pass the function returned by onClick as the value of the onClick prop.

This is more efficient since the onClick callback won’t be created new on every render.

Conclusion

One way to pass a value to the onClick callback is to pass in a function that calls another function into the onClick prop.

A more efficient way to achieve the same result would be to create a function outside the onClick prop and pass it in.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

3 replies on “How to Pass a Value to the onClick Callback in a React Component?”

Hey this was exactly i was looking for . Just one doubt when I call onClick(“clicked”). Will this not always return a new function? The onlick handler will still get the a new function and cause a re render

We set onClick to a function that calls onClick, so it won’t re-render until you click the button.

Leave a Reply

Your email address will not be published.