0

How can I access a data attribute associated with a button from the onClick event handler of the button? Please see the code snippet below.

function ComponentWithAttribute () {
    
function OnClicked() {

    alert("Value of data-val here"); 
  }
    return (
        <button
          onClick={OnClicked}
          data-value={'foo'}
         >
            Click Me!
         </button>
    )
}
export default ComponentWithAttribute;

1
  • This is clearly an antipattern. Place any data you need with your callback in the closure. Commented Jul 28, 2021 at 7:05

3 Answers 3

2

Using the event argument which is passed to any event handler:

function OnClicked(event) {
alert("Value of data-val here " + event.target.getAttribute("data-value"));   
};
Sign up to request clarification or add additional context in comments.

Comments

1

Modify your function to accept event and access using dataset.

function onClicked(e) {
    console.log(e.target.dataset)
}

Comments

0

You should not use data attribute in button tag, instead directly pass that value to function parameter, This can be a dynamic value if you need it

function ComponentWithAttribute () {
                    
  function OnClicked(data) {
    console.log("Value of data-val here", data); 
  }
  return (
    <button onClick={() => OnClicked('foo')}>
     Click Me!
    </button>
  )
                }
export default ComponentWithAttribute;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.