Reactjs -How can recognise which button was clicked?

I have three buttons

<button>A</button>
<button>B</button>
<button>C</button>

I want to have one handler function that takes the action based on clicked button

const clickHandler=()=>{
      if(A was clicked)
               do this 
      if (B was clicked)
               do this
      if (C was clicked)
                do this
}

how do I recognize which button was clicked?

here:

export default function App() {
  const handleButtonCLick = (e) => {
    console.log(e.target.id);
  };
  return (
    <div className="App">
      <button id={1} onClick={(e) => handleButtonCLick(e)}>
        A
      </button>
      <button id={2} onClick={(e) => handleButtonCLick(e)}>
        B
      </button>
      <button id={3} onClick={(e) => handleButtonCLick(e)}>
        C
      </button>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
1 Like

Thanks for your solution.
quick question,
Can I have just a numeric id or it can be a string? do I have to wrap them up in braces or just within the quote
can I have this ?

<button id="mealType">A</button>

go to codesandbox choose react, you can play with it copy and paste my sample from above

Never mind, it’s working thanks for your answer.

1 Like