Search code examples
javascriptreactjseventsevent-handlingpreventdefault

How to use event.preventDefault() when function have arguments


i have a code like this:

const upListCandy = (candy) => {
      /* How i add event.preventDefault() and it word*/
      axios.post("example.com", {
         candyName: candy.name
       }).then().catch()
    }

here is my button:

dataCandy?.map((item, index) => {
   return(
      <div key={index}>
        <button onClick = {() => upListCandy(item)}>{item.name}</button>
      </div>
    )   
 })

And my question is how add parameter of event then event.preventDefault() work?


Solution

  • modify your onclick like so

    <button onClick = {(e) => upListCandy(item,e)}>{item.name}</button>
    

    and then

    const upListCandy = (candy,event) => {
          event.preventDefault();
          axios.post("example.com", {
             candyName: candy.name
           }).then().catch()
        }