Skip to content

Instantly share code, notes, and snippets.

@shovon
Last active March 28, 2022 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shovon/0ad9af418ff0708ef2baf93413a53e5f to your computer and use it in GitHub Desktop.
Save shovon/0ad9af418ff0708ef2baf93413a53e5f to your computer and use it in GitHub Desktop.
An input element that expands as you type into it
import { useEffect, useRef, useState } from "react";
export default function ExpandableInput(
props: React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>
) {
const [value, setValue] = useState(props.value);
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
setValue(props.value);
}, [props.value]);
useEffect(() => {
if (inputRef.current) {
const style = inputRef.current.style;
style.width = "0";
const desiredWidth = inputRef.current.scrollWidth;
style.width = `${desiredWidth + inputRef.current.offsetWidth / 2}px`;
}
}, [value]);
return (
<input
ref={inputRef}
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
style={{ boxSizing: "border-box", ...(props.style || {}) }}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment