mirror of
https://github.com/muerwre/vault-frontend.git
synced 2025-04-25 04:46:40 +07:00
fixed ref forwarding on textareas
This commit is contained in:
parent
2b7b756212
commit
140e36b6b7
5 changed files with 58 additions and 44 deletions
|
@ -1,11 +1,10 @@
|
|||
import React, {
|
||||
ChangeEvent,
|
||||
DetailedHTMLProps,
|
||||
memo,
|
||||
forwardRef,
|
||||
TextareaHTMLAttributes,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import classNames from 'classnames';
|
||||
|
@ -13,6 +12,7 @@ import autosize from 'autosize';
|
|||
import styles from './styles.module.scss';
|
||||
|
||||
import { InputWrapper } from '~/components/input/InputWrapper';
|
||||
import { useForwardRef } from '~/hooks/dom/useForwardRef';
|
||||
|
||||
type IProps = DetailedHTMLProps<
|
||||
TextareaHTMLAttributes<HTMLTextAreaElement>,
|
||||
|
@ -27,20 +27,23 @@ type IProps = DetailedHTMLProps<
|
|||
title?: string;
|
||||
};
|
||||
|
||||
const Textarea = memo<IProps>(
|
||||
({
|
||||
placeholder,
|
||||
error,
|
||||
minRows = 3,
|
||||
maxRows = 30,
|
||||
className,
|
||||
handler,
|
||||
title = '',
|
||||
value,
|
||||
...props
|
||||
}) => {
|
||||
const Textarea = forwardRef<HTMLTextAreaElement, IProps>(
|
||||
(
|
||||
{
|
||||
placeholder,
|
||||
error,
|
||||
minRows = 3,
|
||||
maxRows = 30,
|
||||
className,
|
||||
handler,
|
||||
title = '',
|
||||
value,
|
||||
...props
|
||||
},
|
||||
forwardRef
|
||||
) => {
|
||||
const ref = useForwardRef(forwardRef);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
const onInput = useCallback(
|
||||
({ target }: ChangeEvent<HTMLTextAreaElement>) => handler(target.value),
|
||||
|
@ -52,20 +55,21 @@ const Textarea = memo<IProps>(
|
|||
|
||||
useEffect(() => {
|
||||
if (!ref?.current) return;
|
||||
autosize(ref.current);
|
||||
return () => autosize.destroy(ref.current);
|
||||
autosize(ref?.current);
|
||||
return () => autosize.destroy(ref);
|
||||
}, [ref]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!ref.current) return;
|
||||
if (!ref?.current) return;
|
||||
|
||||
autosize.update(ref.current);
|
||||
}, [value]);
|
||||
autosize.update(ref);
|
||||
}, [ref, value, forwardRef]);
|
||||
|
||||
return (
|
||||
<InputWrapper title={title} error={error} focused={focused} notEmpty={!!value}>
|
||||
<textarea
|
||||
{...props}
|
||||
ref={ref}
|
||||
style={{
|
||||
...props.style,
|
||||
minHeight: minRows * 20,
|
||||
|
@ -74,7 +78,6 @@ const Textarea = memo<IProps>(
|
|||
placeholder={placeholder}
|
||||
className={classNames(styles.textarea, className)}
|
||||
onChange={onInput}
|
||||
ref={ref}
|
||||
onFocus={onFocus}
|
||||
onBlur={onBlur}
|
||||
/>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue