react-hook-form provides its own onChange
handler which it’ll pass as a part of props
, which is likely clobbering your custom handler when you spread props
into the textarea props.
You should instead extract onChange from props and define your own onChange callback which invokes it if it were passed in, rather than spreading it into your props.
export const Textarea = React.forwardRef(
(
{ id, maxLength = 200, onChange, ...props }: TexareaProps,
ref: React.ForwardedRef<HTMLTextAreaElement>
) => {
const { textareaRefSetter } = useTextareaController(ref);
const [count, setCount] = useState(0);
useEffect(() => {
const refElement = document.getElementById(id) as HTMLTextAreaElement;
if (refElement) {
setCount(refElement.value.length);
}
}, [id]);
const onChangeHandler = useCallback(
(event) => {
setCount(event.target.value.length);
onChange?.(event);
},
[setCount, onChange]
);
return (
<div>
<div>
{count}/{maxLength}
</div>
<textarea
id={id}
ref={textareaRefSetter}
onChange={onChangeHandler}
maxLength={maxLength}
{...props}
></textarea>
</div>
);
}
);
CLICK HERE to find out more related problems solutions.