Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify which button clicked in React?

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'
>
like image 292
dany952 Avatar asked Feb 22 '26 13:02

dany952


1 Answers

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

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

And in you listener check the id which button was clicked.

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

Demo:

const { useState } = React;

const Example = () => {

    const onFinish = (event) => {
      let id = event.target.id;
      console.log(`ID: ${id}`);
    }

    return (
        <div>
            <button onClick={onFinish} id={'1'}>Next</button>
            <button onClick={onFinish} id={'2'}>Next</button>
        </div>
    )
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
like image 126
Sanoodia Avatar answered Feb 24 '26 01:02

Sanoodia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!