简体   繁体   中英

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?

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} />

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM