Created
November 1, 2020 19:22
-
-
Save CryceTruly/d8c7165d94b4bcf37d30a6b4f49feed9 to your computer and use it in GitHub Desktop.
react input component with dynamic height
This file contains 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 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