Skip to content

Instantly share code, notes, and snippets.

@i-havr
Last active August 26, 2023 17:16
Show Gist options
  • Save i-havr/6b8e6f39da421360c6c054c9d2765d61 to your computer and use it in GitHub Desktop.
Save i-havr/6b8e6f39da421360c6c054c9d2765d61 to your computer and use it in GitHub Desktop.
This code allows you to create auto-expanding textarea field without un ugly expanding-corner :)
function getScrollHeight(elm) {
var savedValue = elm.value;
elm.value = "";
elm._baseScrollHeight = elm.scrollHeight;
elm.value = savedValue;
}
export const onExpandableTextareaInput = ({ target: elm }) => {
if (!elm.classList.contains("autoExpand") || !elm.nodeName == "TEXTAREA")
return;
var minRows = elm.getAttribute("data-min-rows") | 0,
rows;
!elm._baseScrollHeight && getScrollHeight(elm);
elm.rows = minRows;
rows = Math.ceil((elm.scrollHeight - elm._baseScrollHeight) / 16);
elm.rows = minRows + rows;
};
.autoExpand {
resize: none;
}
import { onExpandableTextareaInput } from "./auto-expanding-textarea";
import "./index.css";
document.addEventListener("input", onExpandableTextareaInput);
export default function SomePage() {
const handleChange = () => {
console.log("The value was changed!")}
return (
<form>
<label>
Поле 1
<textarea
className="autoExpand"
type="text"
rows={2}
data-min-rows={2}
placeholder="Поле обов'язкове"
name="name"
value={name}
onChange={handleChange}
autoFocus
/>
</label>
</form>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment