Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I access data attribute value using useRef hook?

I can access value of className and id by using boardRef.current.className and boardRef.current.id, but if I use boardRef.current.data-board then I get "cannot read properties of undefined". Is there any way to access data attribute using useRef hook?

import React, {useState, useRef} from 'react';

export default function App() {
  const boardRef = useRef();

  const getData = () => {
    console.log(boardRef.current.data-board);
  }
  getData();

  return (
    <div className="App">
      <h1>Tic Tac Toe</h1>
      <div ref={boardRef} className="board" id="boardOne" data-board="one"></div>
    </div>
  );
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using React#useEffect and Element#getAttribute:

const getData = () => {
  console.log(boardRef.current.getAttribute("data-board"));
};

React.useEffect(() => {
  getData();
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading