Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React e.preventDefault() error, onClick passing value from map

    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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

undefined and values

>Solution :

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> )}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading