How to add and remove a class from an input label using refs?

246 views Asked by At

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!

1

There are 1 answers

4
Unmitigated On

You can add another ref for the <label>.

const labelRef = useRef(null);

<label htmlFor="my-input" ref={labelRef}>My Input</label>

Then, use classList.toggle.

const handleBlur = () => {
    const inputValue = inputRef.current.value;
    labelRef.current.classList.toggle('active', inputValue !== '');
};

However, it is more idiomatic to use state instead, as shown below:

const [labelClass, setLabelClass] = useState('');
const [text, setText] = useState('');
const handleBlur = () => {
    setLabelClass(text !== '' ? 'active' : '');
};
return (
    <div>
      <label htmlFor="my-input" className={labelClass}>My Input</label>
      <input
        type="text"
        id="my-input"
        name="my-input"
        value={text}
        onChange={e => setText(e.target.value)}
        onBlur={handleBlur}
      />
    </div>
);