javascriptreactjsconstantscharactercount

How to create a character counter in react?


I am new and creating something with react for the first time. i want to create a character counter in a textarea in react. The counter should have a maximum length of 800 characters. i created this code, but i don't know how to include const without getting an error message.

import React from 'react'
import { Component } from 'react';

function Counter() {
    return (
      
const rezensionTextArea = document.getElementById('rezension_textarea');
        const zeichenCounter = document.getElementById('zeichen_counter');

rezensionTextArea.addEventListener('input', () => {
         const zeichen = rezensionTextArea.value.length;
         zeichenCounter.textContent = `${zeichen}/800`;
        });
    )
}

export default Counter

Solution

  • Here is an example of textarea with react and useState hook. useState return an array of getter and setter of a state. the text value is stored in text and updated with setState. textarea consume the state in handler with value and onChange parameter respectively.

    import './App.css';
    import { useState } from 'react';
    
    function App() {
      const MAX_TEXT_LENGTH = 800;
      const [text, setText] = useState("");
    
      function handleTextAreaChange(event) {
        const value = event.target.value;
        if (value.length <= MAX_TEXT_LENGTH) {
          setText(value);
        }
      }
      return (
        <div className="App">
          <div>
            {`${text.length}/${MAX_TEXT_LENGTH}`}
          </div>
          <textarea rows={16} cols={64}
            onChange={handleTextAreaChange}
            value={text}>
          </textarea>
        </div>
      );
    }
    
    export default App;