0

I have a button where i want to pass a custom attribute to it. I have used data-*, but it was not showing up in the DOM.

  <div className="btn-group" id="dvConfigure">
                  <button
                    id="btnConfigure"
                    data-id="ppppppp"
                    onClick={() => {
                      onButtonClick("btnConfigure", "Configure");

                      setIsButtonClicked(true);
                    }}
                  >
                    <div className="configureIcon">
                      <Icon name="home" size="small" />
                    </div>
                    <span>{I18n.get("Home")}</span>
                  </button>
  </div>

the corresponding CSS for the code:

.btn-group button {
  border: 0px;
  background-color: #efefef; /* Green background */
  cursor: pointer; /* Pointer/hand icon */
  width: 120px; /* Set a width if needed */
  height: 135px;
  font-size: medium;
  font-weight: 500;
  border-radius: 0em;
  color: #434242;
  display: block; /* Make the buttons appear below each other */
}
.btn-group__active {
  border: 0px;
  background-color: white;
  cursor: pointer; /* Pointer/hand icon */
  width: 120px; /* Set a width if needed */
  height: 135px;
  font-size: medium;
  font-weight: 500;
  border-radius: 0em;
  color: #434242;
  display: block; /* Make the buttons appear below each other */
}
.btn-group__active button:hover {
  background-color: white;
}
.btn-group__active button:active {
  background-color: white;
}

.btn-group button:hover {
  background-color: white;
}
.btn-group button:active {
  background-color: white;
}
.btn-group button:focus {
  background-color: white;
}

FYI, i am using React 16.14.0

I tried fetching the attribute by .getAttribute() method but i was getting null. I even added a event listener "DOMConetentLoaded" so that DOM fully loads and then fetch the element, as below:

  useEffect(() => {
    window.addEventListener("DOMContentLoaded", () => {
      var button = document.getElementById("btnConfigure");
      console.log("loaded!!");
      if (button && button.hasAttribute("data-buttonisClicked")) {
        let data = button.getAttribute("data-buttonisClicked");
        console.log("data", data);
      }
    });
  },[]);

I had the above logic in a function, but i wanted to test , so i have added useEffect for ease.

Where am i going wrong?

Afroz S
  • 16
  • 5
  • 1
    Don't query the DOM, use refs instead. Also, there's no point registering a `DOMContentLoaded` listener within an effect hook; the document has well and truly finished loading by that stage – Phil Aug 10 '23 at 06:09
  • I have tried that also, the element had no custom attribute. So, in desperation, I was trying out things. Thanks by the way, I'll go with refs and update here. – Afroz S Aug 10 '23 at 09:13

0 Answers0