1

I want to access custom attribute value using react hooks

Here is code

<div ref={cardNameRef} value="card-1" card-status="yes">Card 1</div>

<button onClick ={setData} className="btn btn-info">Select</button>

I want to access the card-status value.

Here is what I have tried

......
const cardNameRef = useRef();
 ....
  const setData = () => {
    let status = cardNameRef.current.getAttribute('cardStatus');
    console.log('status', status);
  }

Unfortunately, I get the following status null

What is wrong here?

1
  • 2
    Di you try getAttribute('card-status') Commented Mar 16, 2021 at 1:27

2 Answers 2

3

You can get your custom attribute by below code.

function CustomAttr() {
  const cardNameRef = useRef();
  const setData = () => {
    let status = cardNameRef.current.getAttribute("card-status");
    console.log("status", status);
  };
  return (
    <div>
      <div ref={cardNameRef} value="card-1" card-status="yes">
        Card 1
      </div>

      <button onClick={setData} className="btn btn-info">
        Select
      </button>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

0

As a general rule you need to use an attribute or prop name as is. If you call it card-status, use card-status. If you call it cardStatus then use cardStatus. So this should work:

let status = cardNameRef.current.getAttribute('card-status');

In your case, card-status is not a standard div attribute anyway. I would suggest to change it to data-status or data-cardStatus.

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.