Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display character count inside textarea in React?

I’ve been trying to make a "fake" textarea to show character count "inside" of my textarea, like this, but can’t figure out how to make it focus properly.

My solution was to create a parent div with textarea styles, a textarea with no styling and a character counter to make a fake textarea:

<div> // textarea styling
  <textarea />
  <div style={{display: 'flex', justifyContent: 'flex-end'}}>{counter}/2000</div>
</div>

It looks like the example above, but I have problems with focusing on the parent div. I need to visually show that it is in focus.
I’ve used a useRef hook to focus the parent div but it doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const ref = useRef(null);

<div ref={ref}>
  <textarea onClick={() => ref.current.focus()} />
  //...
</div>

Here is an example https://codesandbox.io/p/sandbox/custom-textarea-ypl4rj

Is it even possible to trigger a focus state for a div? Maybe I’m using a wrong event?

>Solution :

Not all HTML elements can receive focus – see this answer.

Instead, change the style of ref-parent to use :focus-within instead of :focus (sandbox):

.ref-parent:focus-within {
  border: 1px solid blue;
  outline: 1px solid blue;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading