Search code examples
javascriptreactjs

How can I pass other arguments to event handler in React?


I was trying to pass both the event and some other data (the index of an element) to an event handler in a React App. I found here that I should make a higher-order function, but I don't get a pleasant result. Here is a snippet of my code:

  const changeNameHandler = (index) => {
    return (event) => {
      console.log(index, event);
    };
  };

  let persons = null;

  if(showValuesState) {
    persons = (
      <div>
        {
          personsState.map((person, index) => {
            return <Person
              name = {person.name}
              age = {person.age}
              click = {() => deletePersonHandler(index)}
              key = {index}
              changeName = {() => changeNameHandler(index)()}/>
          })
        }
      </div>
    );
  }

I am trying to pass the index to changeNameHandler function while also getting the event, but the value of the event variable from that console.log(index, event) statement is still undefined.


Solution

  • when ever you are calling a function from inside your jsx, if you wanted to pass extra values rather that the event, you have to consider doing like below:

    changeName = {() => changeNameHandler(index)}/>
    
    

    Also the important point is that you are getting the function hooked up on the changeName prop of your Person component but you don't capture the event value from it, so if you need to access the event value inside of your handler you have to do it like below:

    changeName = {(evt) => changeNameHandler(evt, index)}/>
    
    

    and by doing this you will get the event as first argument and he index value as second argument in your handler.

    const changeNameHandler = (evt, index) => {
      // do what ever you want here with values 
    }