Skip to content

Commit

Permalink
fix textarea input ref
Browse files Browse the repository at this point in the history
  • Loading branch information
steppy452 committed Aug 11, 2024
1 parent c8ae8ae commit b3974e5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
14 changes: 13 additions & 1 deletion src/form/Textarea/Textarea.story.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { useRef } from 'react';
import { Stack } from '../../layout/Stack';
import { Textarea } from './Textarea';
import { Button } from '@/elements';

export default {
title: 'Components/Form/Textarea',
Expand Down Expand Up @@ -32,3 +33,14 @@ export const Sizes = () => (
<Textarea value="Large" size="large" />
</Stack>
);

export const OutsideFocus = () => {
const inputRef = useRef(null);

return (
<Stack direction="column">
<Button onClick={() => inputRef?.current.focus()}>Click to focus</Button>
<Textarea ref={inputRef} />
</Stack>
);
};
18 changes: 12 additions & 6 deletions src/form/Textarea/Textarea.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, {
FC,
import {
forwardRef,
RefObject,
useImperativeHandle,
useLayoutEffect,
useRef
} from 'react';
import TextareaAutosize, {
Expand Down Expand Up @@ -61,17 +61,15 @@ export interface TextAreaRef {
focus?: () => void;
}

export const Textarea: FC<TextareaProps & TextAreaRef> = forwardRef<
TextAreaRef,
TextareaProps
>(
export const Textarea = forwardRef<TextAreaRef, TextareaProps>(
(
{
fullWidth,
size = 'medium',
containerClassName,
className,
error,
autoFocus,
theme: customTheme,
...rest
},
Expand All @@ -87,6 +85,13 @@ export const Textarea: FC<TextareaProps & TextAreaRef> = forwardRef<
focus: () => inputRef.current?.focus()
}));

useLayoutEffect(() => {
if (autoFocus) {
// Small timeout for page loading
requestAnimationFrame(() => inputRef.current?.focus());
}
}, [autoFocus]);

const theme: TextareaTheme = useComponentTheme('textarea', customTheme);

return (
Expand All @@ -108,6 +113,7 @@ export const Textarea: FC<TextareaProps & TextAreaRef> = forwardRef<
theme.sizes[size],
className
)}
autoFocus={autoFocus}
{...rest}
/>
</div>
Expand Down

0 comments on commit b3974e5

Please sign in to comment.