Home > Mobile >  How can I access data attribute value using useRef hook?
How can I access data attribute value using useRef hook?

Time:11-14

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>
  );
}

CodePudding user response:

Using React#useEffect and Element#getAttribute:

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

React.useEffect(() => {
  getData();
}, []);
  • Related