Parameter

onClick with a parameter in React

It can be difficult to understand just how to pass a parameter to a React function from an onClick call, and it can even be more confusing to know if you’re going about it in the right way.

But what is the “right” way?

It all depends on your situation. If you’re trying to send a variable value that is currently being rendered on your page you should probably not pass a parameter but use the value (hopefully) currently stored in the state of the component.

For example, when the user clicks the button in the following component, the current value of userId is used in the function getUserInformation:

function OnClickParam() {
  const api = new API();
  const [userId, setUserId] = useState(0);

  const onClickFunction = () => {
    console.log(api.getUserInformation(userId));
  }

  return (
    <div>
      <h1>{userId}</h1>
      <button onClick={onClickFunction}>Click me</button>
    </div>
  )
}

If you just want to send some static information related to your button then you can just set the value attribute of the button and use the Javascript event syntax to read the value and pass it to your function. For example:

function OnClickParam() {
  return (
    <div>
       <button value="pass this to the function" onClick={event => api.updateButtonData(event.target.value)}>Click me</button>
    </div>
  );
}

This becomes particularly useful when you are dealing with a collection of information inside an array or similar construct. Take the following component for example:

function OnClickParam() {
  const myCollectionOfData = [
    {
      id: 0,
      name: "Bernie",
      role: "Learning",
    },
    {
      id: 1,
      name: "Statler",
      role: "Heckler",
    },
    {
      id: 2,
      name: "Lou",
      role: "Musician",
    },
  ];

  return (
    <div>
      {myCollectionOfData.map((person) => {
        return <div key={person.id}>
          <h1>{person.name}</h1>
          <button onClick={() => alert(person.role)}>What is my role?</button>
        </div>;
      })}
    </div>
  );
}

The component OnClickParam first defines some collection of data named myCollectionOfData. The component renders a div for each element in the myCollectionOfData array that contains a header of the person’s name and a button to alert the user of the person’s role.

If you look at the button definition you can see that an alert is called when clicked and the value that is being passed to onClick is data coming from my collection.

These are just two ways to send data to a function. Based on the different scenarios shown above, these are the “right” enough for what you need to do. In a future post, I will work through why inline function definitions may cause unnecessary re-renders in your application, but also when you should actually worry about that.

Leave a Reply

Your email address will not be published. Required fields are marked *