Home > front end >  React e.preventDefault() error, onClick passing value from map
React e.preventDefault() error, onClick passing value from map

Time:01-24

    const onSubmit = (event, val) => {
    console.log(val);
    event.preventDefault();
    setValues({ ...values, error: "", success: "", key: val });
    setDidSubmit(true);
  };

Using map in React:

{data.map((e) => ( <li key={e._id}> <button
                        onClick={(e) => onSubmit(e, e._id)}
                        className="btnx btn-primary"
                      >
                        Book Now logout
                      </button> </li> )}

onClick I want to pass unique id e._id to the onSubmit function.

But I'm getting output as undefined.

undefined and values

CodePudding user response:

Edit :- can you also please provide the output of e argument that you passed into the map callback ?

onClick takes a callback function and pass event as its parameter . Now , here the problem what if i want take some other parameter , to overcome this problem we have to wrap the function (can be accomplished by anonymous function or some other defined function in the code ) -> this step you did the correct but thing you did wrong is that you did not accounting the onClick callback default parameter i.e event . so you must account the event parameter in your wrapping function , then you can able to access the event object.

I hope so you get the answer.

{data.map((e) => ( <li key={e._id}> <button
                        onClick={(event) => onSubmit(event, e._id)}
                        className="btnx btn-primary"
                      >
                        Book Now logout
                      </button> </li> )}
  • Related