React Ref The Input Name

So I have a bunch of checkboxes representing movie genres and I was wondering if there is a way to reference the name of the checkbox like for the one below the ref should give me the name Action.

 <input
          ref={?}
          type="checkbox"
          name="Action"
          onChange={handleCheck}
        />
    Action
    <img src={require('../../../images/action.jpg')} className="action" alt="logo"/>

I am also open to other ideas not just ref to get the name of the checkbox.

You can get event.target.name inside the handler.

If you use refs you have to create a ref per element. Depending on how many you have, an array of refs might be the better option.


Event

function App() {
  const handleChecked = ({ target }) => {
    console.log(target.name); // name1
  };
  
  return (
    <div>
      <input type="checkbox" name="name1" onChange={handleChecked} />
    </div>
  );
}

Ref

import { useRef } from 'react';

function App() {
  const inputRef = useRef(null);

  const handleChecked = () => {
    console.log(inputRef.current.name); // name1
  };

  return (
    <div>
      <input
        ref={inputRef}
        type="checkbox"
        name="name1"
        onChange={handleChecked}
      />
    </div>
  );
}

Alright your solution with refs seems to work.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.