Search code examples
reactjsreact-hooksfocustextarea

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.

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