DEV Community

Cover image for Autosize Input Field - Plain JS and React Examples
zechdc
zechdc

Posted on

Autosize Input Field - Plain JS and React Examples

You want an input field that automatically grows and shrinks with it's contents. Here's some quick examples how to do it with pure Javascript or React (without using another npm package)

Pure Javascript Code Example

https://codepen.io/zechdc/pen/LYvgEod

React Example

InputAutosize.tsx example gif

Component Usage

<InputAutosize
  className="rounded border border-sky-500 px-2 py-0.5"
  value={myValue}
  onChange={(e) => {
    // Set myValue to e.target.value
  }}
/>
Enter fullscreen mode Exit fullscreen mode

InputAutosize component code:

// link: https://gist.github.com/zechdc/edc9797dcc50df1c9b54f3738a00e7df

import { cn } from "~/lib/shadcnui";

interface InputAutosizeProps
  extends React.InputHTMLAttributes<HTMLInputElement> {
  value: string;
}

export default function InputAutosize({
  className,
  value,
  ...props
}: InputAutosizeProps) {
  return (
    <div className={cn("grid", className)}>
      <span className="invisible" style={{ gridArea: " 1 / 1 " }}>
        {!value && "\u00A0"}
        {value.replace(/ /g, "\u00A0")}
      </span>
      <input
        size={1}
        style={{ gridArea: " 1 / 1 " }}
        type="text"
        value={value}
        className={`border-none bg-transparent focus:outline-none`}
        {...props}
      />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Note: .replace(/ /g, "\u00A0") replaces spaces with   to avoid flickering of content.

Sources:

Top comments (0)