birolaygün
birolaygün

Reputation: 24

How Can I Get Name Attribute In React

I need to get name atribute in button element. I can get it from DOM but I dont want to do that. If there is a easy way to get name atribute please help me. ( I use functional Component )

<button name="elementsName"> elementsName <button/>

Upvotes: 0

Views: 696

Answers (1)

Alpha
Alpha

Reputation: 1467

You can use a hook call useRef to access element properties.

Read more about useRef

Solution:

Simply create useRef in your component and bind it with your button and access its properties

Example:

import React, { useRef } from "react";

const App = ({ ...props }) => {
  const buttonRef = useRef(null); 
  const hanldeGetButtonRef = () => {
    console.log("button REF ==>", buttonRef.current.name);
  };
  return (
    <div onClick={hanldeGetButtonRef}>
      <button name="elementsName" ref={buttonRef}>
        CLICK
      </button>
    </div>
  );
};

export default App;

Upvotes: 2

Related Questions