Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!