I have a React component that includes an input element and a corresponding label element. I want to add and remove a class from the label element based on whether the input element has a value or not. I'm using useRef to reference the input element in my component. How can I add and remove the class from the label element using useRef?
Here's my current code:
import { useRef } from "react";
const MyComponent = () => {
const inputRef = useRef(null);
const handleBlur = () => {
const inputValue = inputRef.current.value;
if (inputValue === "") {
// TODO: remove "active" class from label element
} else {
// TODO: add "active" class to label element
}
};
return (
<div>
<label htmlFor="my-input">My Input</label>
<input
type="text"
id="my-input"
name="my-input"
ref={inputRef}
onBlur={handleBlur}
/>
</div>
);
};
I've omitted the implementation for adding and removing the class from the label element because I'm not sure how to do it using useRef. Any help would be appreciated!
You can add another
reffor the<label>.Then, use
classList.toggle.However, it is more idiomatic to use state instead, as shown below: