I am currently working on developing a registration form using React and Tailwind CSS. As part of this project, I have implemented a feature where the label slides up when an input form is focused. Everything seems to be working fine up to this point. However, I encountered an issue where if I focus on another input, the label of the previously selected input reverts back to its original position, essentially acting as a placeholder. Here are the relevant sections of my code:
<div className="relative mb-4">
<input
type="text"
id="username"
name="username"
value={formData.username}
onChange={handleChange}
className="peer p-3 h-10 w-full border-b-2 border-gray-300 text-gray-900 placeholder-transparent focus-within:outline-none focus-within:border-rose-600"
placeholder=""
required
/>
<label
htmlFor="username"
className={`absolute left-1 top-2 transition-all text-gray-400 ${formData.username.length > 0 ? 'text-md' : 'text-base'
} ${formData.username.length > 0 ? 'text-gray-400' : ''
} peer-focus-within:left-0 peer-focus-within:-top-6 peer-focus-within:text-gray-700 peer-focus-within:text-md peer-focus-within:text-bold`}
>
Username
</label>
</div>
Screenshots
The issue can be clearly seen in the fourth screenshot provided. Any suggestions on how to address this problem would be greatly appreciated! Thank you in advance!
I attempted to use template strings and ternary operators for some conditional checks, but unfortunately, I was unable to resolve the issue.