What is the best way to anchor floating labels in React while incorporating Tailwind CSS?

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.

Answer №1

Sorry if I misunderstood the issue you're facing, but it appears that you'd like the label to remain in a fixed position once the user is ready. Currently, the label's position change is triggered by the

peer-focus-within:-top-6

However, the problem arises when the focus is removed. In such cases, the focus within rule no longer applies and the original style takes precedence.

There are several ways to address this. One suggestion is to simplify your styling logic based on the username length, like so:

  className={`absolute transition-all ${formData.username.length === 0 ? 'left-1 top-2 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' : 'left-0 -top-6 text-gray-700 text-md text-bold'}`}

Once the transition occurs, the classname will permanently switch to the same value so it won't revert back.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

What is the correct way to designate my classname prior to the expression?

I am having trouble getting styles.nav__item to work properly in the code snippet below. Can someone help me fix this so I can continue styling? import Link from "next/link"; import React from "react"; import styles from '../styles ...

You may encounter an error in React where e.target.value is not defined when

const validationSchema = yup.object({ password: yup .string('Enter your password') .min(8, 'Password should be at least 8 characters long') .required('Password is required'), }); const formik = useFormik({ ...

CSS Begin the background repeat from a specific origin

I am trying to achieve a specific background effect starting from the line shown in the screenshot below: I attempted to implement it using the following CSS code: background : ('path/to/image') 0 650px repeat-y However, the light part of the ...

What is the best way to set up the makeStyles hook in material-ui using a custom JSS insertion point?

tag: After wrapping my react component and releasing it as a web component, I encountered an issue where styles created using makeStyles hook were not being applied because they were inserted into the head section of the browser DOM. Is there a way to con ...

Webpack: Embed font file directly into index.html

Currently, I am utilizing the html-webpack-plugin and my goal is to add my hashed font file into my customized index.html template. index.html <!DOCTYPE html> <html lang="en"> <head> <style> @font-face { f ...

What is the reason for receiving an undefined value when calling getInitial

In my index page like this: function Index({posts}) { console.log(posts); return ( <div> Homepage {/* {posts && posts.length > 0 && posts.map(post => <h1 key={post._id}>{ post.title} ...

How come my label and input are showing up in my navigation bar?

For my assignment, I am designing a website layout and facing an issue where the text appears behind the navigation bar instead of below it. I have tried adjusting the margin-bottom to 50px with important tags and setting the nav bar as static. Despite tr ...

My goal is to dynamically assign a class to an iframe element by identifying a specific class contained within the html of the iframe

I need assistance with adding a class to an iframe only if the body tag has a specific class name. Here is my attempt at writing some code: <iframe class='iframeContent' src='' width='100%' height='' frameborder= ...

Getting Bootstrap column width using SASS

Is there a way to make a title in one column overlap the next column without relying on position:absolute in CSS? I want to maintain the width of the title to be as wide as the col-8 column in Bootstrap, while keeping it proportional for smaller screens. A ...

Implementing unique metadata tags for Next.js version 13

Can custom metatags be created with Next 13 and the ability to control if it should be labeled as "name" or "property"? I attempted to add Facebook metatags such as 'og:updated_time', but that specific key is not available. Using 'other&apo ...

What could be the reason behind the background-image not functioning properly in this case?

Would you mind taking a look at this link? http://jsfiddle.net/BbkBf/ I have a couple of questions: 1. Why is the background-image not displaying for the first one? (Even if the a tag is empty, it should still work) 2. Why isn't the image being ...

Having trouble locating the issue in my React application

As part of a tutorial project, I am developing an e-Commerce application using React. Currently, I am encountering an error message stating 'TypeError: Cannot read property 'length' of undefined' when dealing with a cart object. Let me ...

Is it possible to insert a button into a specific column of an ngx-datatable within an Angular 8 application?

I am having trouble with this particular HTML code. <ngx-datatable-column name="Option" prop="option" [draggable]="false" [resizeable]="false [width]="250"> <span> <button class="optionButton" type="button" data-to ...

What is the best method for retrieving environment variables within a React JS web application?

Within my render method, I am trying to access a specific environment variable. However, because it is a custom ENV variable, I cannot utilize (process.env.NODE_ENV). According to this source, React filters all process.env access. What would be the best w ...

Encountering an issue with Next.js where the document is not defined while using react-org-chart

Every time I attempt to implement the react-org-chart, I encounter an error message stating "document is not defined." Currently, I am utilizing Next.js for my project. Below is a snippet of the code that I have been working on: import SidebarDesktop from ...

PNPM and Storybook error: No configuration files were detected in the specified config directory

I am facing challenges setting up a Storybook documentation project in my PNPM monorepo. I have attempted to add it to an existing app and create a new project, but encountered the same error message both times: Error: No configuration files have been fou ...

Connecting Node.Js and Express with React for a Seamless Backend-Frontend Integration

Looking for advice on merging two projects - one for React frontend and the other for NodeJs Express backend. Currently, I am using Android Studio to preview my front-end application on a phone emulator but unsure of how to make everything work together se ...

What is the best way to handle errors from mysql queries in an Express application when using a React form?

I have been facing an issue while trying to direct users to different pages based on the success or failure of an SQL query in an Express backend. Only the route for success seems to be working when using this code. Even without the await statement, I enc ...

Switching language in nextjs without altering the URL

Is it possible to switch languages in Next.js without requiring a language parameter in the URL format such as baseurl/ar or baseurl/en? I am looking to change the language from a dropdown menu without affecting the URL. ...