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

196
Views
useRef for showing the count of characters inside a textarea

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

0

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]);
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!