how to identify which button clicked in react?

Viewed 2286

I have two buttons that execute the same function, and that function needs to evaluate go backward or go forward as I show in the following image

enter image description here

and in the following code I want to evaluate what function next() or prev() to execute depending on which button was touched, this is built in react

const onFinish = (values) => {

if (values.users) {
  const Operator = values.users.map((item) => ({
    ruleAttributeName: item.ruleAttributeName,

    isoAttributeId: item.isoAttributeId,

    ruleOperationId: item.ruleOperationId,

    mandatoryValue: item.mandatoryValue,
  }));
  setAttributes(Operator);
}
if (values.users) {
  const attributesSave = values.users.map((item) => ({
    ruleAttributeName: item.ruleAttributeName,
    isoAttributeEntity: {
      isoAttributeId: item.isoAttributeId,
    },
    ruleOperationEntity: {
      ruleOperationId: item.ruleOperationId,
    },
    mandatoryValue: item.mandatoryValue,
  }));
  console.log('mandatory';
  setAttributesSave(attributesSave);
  setMandatoryValue();
  next();
  prev();
   };

and in this form I pass by parameter the function

<Form
  name='dynamic_form_nest_item'
  onFinish={onFinish}
  autoComplete='off'
>
2 Answers

You can identify them by assigning unique Id to both button like this

<button onClick={onFinish} Id={'1'}>Next</button>
<button onClick={onFinish} Id={'2'}>Next</button>

And in you listener check id which button clicked.

const onFinish = (event) => {
  Let id = event.target.id;
  if(id=== "1") {
    // Do for one
  } else {
    // For second
  }
}

I don't know the parameters that you got on that custom buttons and how is it triggering onClick event. But here is the solution for HTML buttons.

You can set a value to the button like this.

<button onClick={onFinish} value="next">Next</button>

const onFinish = (ev) => {
  ev.preventDefault() // this is to prevent the refresh
  
  const { value } = ev.target // equals with const value = ev.target.value
  if(value === "next") {
    next()
  } else {
    prev()
  }
}
Related