Skip to content

Commit 8fe003d

Browse files
siddharthkpSaraVieira
authored andcommitted
components: autosize for textarea (codesandbox#3306)
* autosize for textarea * forgot to remove props
1 parent d670906 commit 8fe003d

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

packages/components/src/components/Textarea/index.stories.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,9 @@ export const onChange = () => (
4242
/>
4343
</Wrapper>
4444
);
45+
46+
export const autoResize = () => (
47+
<Wrapper>
48+
<Textarea autosize placeholder="Write a lot of lines here" />
49+
</Wrapper>
50+
);

packages/components/src/components/Textarea/index.tsx

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,21 @@ interface ITextareaProps
1414
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
1515
label?: string;
1616
maxLength?: number;
17+
autosize?: boolean;
1718
}
1819

1920
export const TextareaComponent: any = styled(InputComponent).attrs({
2021
as: 'textarea',
2122
})(
2223
css({
23-
height: 64,
24+
minHeight: 64,
2425
padding: 2,
2526
width: '100%',
2627
resize: 'none',
28+
// no transition because it breaks autoshrink :(
29+
// leaving this comment here to save time of the brave
30+
// soul who tries this again
31+
// transition: 'height 150ms',
2732
})
2833
) as StyledComponent<
2934
'textarea',
@@ -45,6 +50,7 @@ export const Textarea: React.FC<ITextareaProps> = ({
4550
maxLength,
4651
onChange,
4752
onKeyPress,
53+
autosize,
4854
...props
4955
}) => {
5056
const id = props.id || uniqueId('form_');
@@ -67,6 +73,8 @@ export const Textarea: React.FC<ITextareaProps> = ({
6773
} else {
6874
setValue(e.target.value);
6975
}
76+
77+
if (autosize) resize(e.target as HTMLTextAreaElement);
7078
};
7179

7280
const keyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
@@ -80,6 +88,12 @@ export const Textarea: React.FC<ITextareaProps> = ({
8088
return true;
8189
};
8290

91+
const resize = (element: HTMLTextAreaElement) => {
92+
const offset = 2; // for borders on both sides
93+
element.style.height = ''; // reset before setting again
94+
element.style.height = element.scrollHeight + offset + 'px';
95+
};
96+
8397
return (
8498
<>
8599
{props.placeholder && !label ? (

0 commit comments

Comments
 (0)