Next.js Discord

Discord Forum

Character Counter Component

Unanswered
West African Crocodile posted this in #help-forum
Open in Discord
West African CrocodileOP
I want to separate TextArea.tsx into two distinct components, TextArea.tsx and CharacterCounter.tsx, that can seamlessly integrate into a Form. This separation will enable easier maintenance and reuse of code and I can easily declare which input that character counter will count.

Ive tried for two hours to separate the component into two components but nothing has worked.

I am using react-hook-form.

``ts import { useState } from 'react' import { FieldError, UseFormRegisterReturn } from 'react-hook-form' interface TextAreaProps { error?: FieldError id: string label: string maxLength: number placeholder?: string register: UseFormRegisterReturn rows?: number title?: string } export default function TextArea({ error, id, label, maxLength, placeholder, register, rows = 5, // default rows to 5 title, }: TextAreaProps) { const [characterCount, setCharacterCount] = useState(0) const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { setCharacterCount(event.target.value.length) } return ( <li> {label && ( <label className="block mb-1" htmlFor={id}> {label} </label> )} <textarea className="bg-gray-800 outline-none p-3 rounded-md w-full" id={id} placeholder={placeholder} rows={rows} title={title} {...register} onChange={handleInputChange} ></textarea> <span className={text-sm ${characterCount > maxLength ? 'text-red-500' : 'text-gray-400'
}`}
>
{characterCount}/{maxLength} characters
</span>
{error && <p className="mt-1 text-sm text-red-500">{error.message}</p>}
</li>
)
}
'''

0 Replies