Last active
March 28, 2022 03:50
-
-
Save shovon/0ad9af418ff0708ef2baf93413a53e5f to your computer and use it in GitHub Desktop.
An input element that expands as you type into it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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