Home > front end >  How to use event.preventDefault() when function have arguments
How to use event.preventDefault() when function have arguments

Time:03-23

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?

CodePudding user response:

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()
    }

CodePudding user response:

I think you can change it like this

dataCandy?.map((item, index) => {
   return(
      <div key={index}>
        <button onClick = {(e) => upListCandy(e,item)}>{item.name}</button>
      </div>
    )   
 })
const upListCandy = (e,ceandy) => {
      e.preventDefault()
      axios.post("example.com", {
         candyName: candy.name
       }).then().catch()
    }
  • Related