Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda