Search code examples
reactjsreact-hook-formwatch

count character with react-hook-form watch


Currently, I am using react-hook-form for form transmission. and, I want to render the number of characters included in input and textarea.

The code I implemented is as follows.

<input
  id="title"
  type="text"
  placeholder="title"
  {...register('title', {
    required: true,
  })}
/>
<span>
  {watch('title').length}/20
</span>

As shown above, I tried to render the number of characters input through watch, but failed. How do you represent the number of characters?


Solution

  • Update your watch with the condition for undefined.

    { watch('title') ? (watch('title').length)/20 : '' }
    

    Can check working code from here : https://stackblitz.com/edit/stackoverflow-095?file=src%2FApp.jsx