Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
useRef para mostrar el recuento de caracteres dentro de un área de texto

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 chars

Pero, ¿cómo se puede hacer con useRef?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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} />
about 4 years ago · Santiago Trujillo Denunciar

0

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]);
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda