Having the following component:
import React from 'react';
export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
maxLength?: number;
id: string;
}
export const Textarea = React.forwardRef(
(
{ id = 'my-id', maxLength = 200, ...props }: TexareaProps,
ref: React.ForwardedRef<HTMLTextAreaElement>
) => {
return (
<div className='relative flex flex-col'>
<textarea id={id} maxLength={maxLength} {...props}></textarea>
</div>
);
}
);
export default Textarea;
It returns a textarea where a user can write up to 200 characters. My aim is to show somewhere the current count of written characters, so in order to do that the component must use useRef
hook to access the textarea.
In plain JS it would be like:
const toCheck = document.getElementById('my-id');
console.log(toCheck.value.length); // this will log the current count of written chars
But how can it be done with useRef?
CodePudding user response:
pass ref to textarea
<textarea ref={ref} id={id} maxLength={maxLength}{...props}></textarea>
and you can use component Textarea
like this
const textAreaRef = useRef<HTMLTextAreaElement>()
console.log(textAreaRef.current?.value.length)
return <Textarea ref={textAreaRef} />
CodePudding user response:
You can do it like this
import React from "react";
export interface TexareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
maxLength?: number;
id: string;
}
export const Textarea = React.forwardRef(
(
{ id = "my-id", maxLength = 200, ...props }: TexareaProps,
ref: React.ForwardedRef<HTMLTextAreaElement>
) => {
return (
<div className="relative flex flex-col">
<textarea {...props} ref={ref} id={id} maxLength={maxLength}></textarea>
</div>
);
}
);
export default Textarea;
and then in the parent, you can show the number of character
const textAreaRef = useRef();
useEffect(() => {
if (textAreaRef.current) {
console.log(textAreaRef.current.value.length);
}
}, [textAreaRef]);