-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
29 additions
and
24 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,38 @@ | ||
import React, { useEffect, useRef } from 'react'; | ||
import React, { useEffect, useRef, useState } from 'react'; | ||
|
||
export default function AutoResizeTextArea({defaultValue, keepWidth, className, ...props}) { | ||
export default function AutoResizeTextArea({ defaultValue, keepWidth, className, ...props }) { | ||
|
||
const textAreaRef = useRef(null) | ||
const textAreaRef = useRef(null); | ||
const [value, setValue] = useState(defaultValue || ''); // Initialize with defaultValue prop | ||
|
||
useEffect(() => { | ||
resize(textAreaRef.current) | ||
}, [defaultValue, resize]) | ||
setValue(defaultValue || ''); // Update value when defaultValue prop changes | ||
}, [defaultValue]); | ||
|
||
useEffect(() => { | ||
resize(textAreaRef.current); | ||
}, [value, resize]); | ||
|
||
/** | ||
* Automatic horizontal and vertical resizing of textarea | ||
* @param {textarea} input | ||
*/ | ||
function resize(input) { | ||
input.style.height = 0; | ||
input.style.height = input.scrollHeight + "px"; | ||
|
||
if(!keepWidth) { | ||
if (!keepWidth) { | ||
input.style.width = "auto"; | ||
input.style.width = input.scrollWidth + "px"; | ||
} | ||
} | ||
|
||
return <textarea className={(className ? className + ' ' : '') + 'autoResize'} ref={textAreaRef} defaultValue={defaultValue} {...props} | ||
onChange={(e) => resize(e.target)} />; | ||
return ( | ||
<textarea | ||
className={(className ? className + ' ' : '') + 'autoResize'} | ||
ref={textAreaRef} | ||
value={value} // Use value instead of defaultValue | ||
onChange={(e) => { | ||
setValue(e.target.value); // Update state when the value changes | ||
resize(e.target); | ||
}} | ||
{...props} | ||
/> | ||
); | ||
} |