Skip to content

Instantly share code, notes, and snippets.

@CryceTruly
Created November 1, 2020 19:22
Show Gist options
  • Save CryceTruly/d8c7165d94b4bcf37d30a6b4f49feed9 to your computer and use it in GitHub Desktop.
Save CryceTruly/d8c7165d94b4bcf37d30a6b4f49feed9 to your computer and use it in GitHub Desktop.
react input component with dynamic height
import React, { useState } from "react";
import "./style.css";
const DynamicHeightInput = () => {
const [textareaHeight, setTextareaHeight] = useState(42);
const [formValue, setFormValue] = useState({});
const onChange = (event) => {
event.preventDefault();
event.persist();
setFormValue({ ...formValue, [event.target.name]: event.target.value });
};
return (
<div className="message-input">
<textarea
placeholder={"Type a message"}
className="textMessageInput"
name="body"
value={formValue.body || ""}
onChange={(e) => {
onChange(e);
const height = document.querySelector('textarea[name="body"]')
?.scrollHeight;
setTextareaHeight(height > 42 ? height : 42);
}}
style={{
minHeight: `${formValue.body ? textareaHeight || 42 : 42}px`,
}}
/>
</div>
);
};
DynamicHeightInput.propTypes = {};
export default DynamicHeightInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment