Teniendo el siguiente componente:
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; Devuelve un área de texto donde un usuario puede escribir hasta 200 caracteres. Mi objetivo es mostrar en alguna parte el recuento actual de caracteres escritos, por lo que para hacerlo, el componente debe usar useRef hook para acceder al área de texto.
En simple JS sería como:
const toCheck = document.getElementById('my-id'); console.log(toCheck.value.length); // this will log the current count of written charsPero, ¿cómo se puede hacer con useRef?
pasar referencia al área de texto
<textarea ref={ref} id={id} maxLength={maxLength}{...props}></textarea> y puedes usar el componente Textarea como este
const textAreaRef = useRef<HTMLTextAreaElement>() console.log(textAreaRef.current?.value.length) return <Textarea ref={textAreaRef} />Puedes hacerlo así
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;y luego en el padre, puede mostrar el número de carácter
const textAreaRef = useRef(); useEffect(() => { if (textAreaRef.current) { console.log(textAreaRef.current.value.length); } }, [textAreaRef]);