Creating floating label for input with tailwind and react

ID

Ideabuzz

Author

June 15, 2022
Share

Create a component with the below code name FloatingLabelInput


import { useState } from "react";

function FloatingLabelInput({ type, name, children, label }) {
    const [active, setActive] = useState(false);
    function handleActivation(e) {
      setActive(!!e.target.value);
    }
    return (
      <div className="relative rounded mb-2 bg-gray-200 text-ciaoamigos_gray ">
          {type == 'select' ?
          <select className={[
            "outline-none w-full rounded bg-transparent text-sm transition-all  h-14 duration-200 ease-in-out p-2",
           "pt-6"
          ].join(" ")}
          id={name}
          name={name}
          type={type}
          onChange={handleActivation}>
              {children}
          </select>
        : <input
          className={[
            "outline-none w-full rounded bg-transparent text-sm transition-all duration-200 ease-in-out h-14 p-2 pl-3",
            active ? "pt-6" : "pt-2"
          ].join(" ")}
          id={name}
          name={name}
          type={type}
          onChange={handleActivation}
        />}
        <label
          className={[
            "absolute top-0 left-0 flex items-center text-white text-opacity-50 pb-2 pl-3 transition-all duration-200 text-ciaoamigos_gray ease-in-out",
            active ? "text-xs pt-3" : type == 'select' ? "text-sm pt-2" : "text-sm pt-4"
          ].join(" ")}
          htmlFor={name}
        >
          {label}
        </label>
      </div>
    );
  }
  export default FloatingLabelInput;

using in the input type text

 <FloatingLabelInput name="name" type="text" label="Name"/>

using in the input type select

                        <FloatingLabelInput name="tag" type="select" label="Tag">
                            <option value="free">Free</option>
                            <option value="Paid">Paid</option>
                        </FloatingLabelInput>