modimo
August 10, 2022, 1:59am
1
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"/>
modimo
August 10, 2022, 2:12pm
2
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>
);
}
modimo
August 17, 2022, 8:02pm
4
Alright your solution with refs seems to work.
system
Closed
February 16, 2023, 8:02am
5
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.