Home > front end >  In react how to detect the button id clicked on not
In react how to detect the button id clicked on not

Time:03-24

In this case when I clicked the button I want to access the button Id and also want to checked that button is clicked or not. here I have use the e.currentTarget.idto detect the button ID and want to checked that its clicked or not by using document.getElementById("yourID").clicked === true. But after clicking the button its not give the alert. So how do I achieved that

import * as React from "react";
export default function Map() {
  const getButtonId = (e) => {
    if (e.currentTarget.id === "yourID") {
      if (document.getElementById("yourID").clicked === true) {
        alert("button clicked");
      }
    }
  };
  return (
    <div>
      <button id="yourID" onClick={getButtonId}>
        Button
      </button>
    </div>
  );
}

CodePudding user response:

First of all there is no need to use document.getElementById("yourID").clicked === true because button has onClick property that you are using which does what you want.

And as to solve your problem, you have a typo in your code. You typed yourId in e.currentTarget.id === "yourID" instead of yourID

const getButtonId = (e) => {
    if (e.currentTarget.id === "yourID") {
        alert("button clicked");
   }
}
  • Related