reactjscharacterlimitcharactercountreact-quill

How to show character counter in a React-quill


I would like to add a character counter on my React Quill. At the moment I have a character limiter of 950. The problem is that the user must be aware that the number of characters must not be more than 950, thus the character counter I've tried adding getLength() on the render but gives me an error. This is my code:

attachQuillRefs = () => {
    if (typeof this.reactQuillRef.getEditor !== "function") return;
    this.quillRef = this.reactQuillRef.getEditor();
  };

  //Handles changes to description field
  handleDetailChange(value) {
    var limit = 950;
    var quill = this.quillRef;
    quill.on("text-change", function (delta, old, source) {
      if (quill.getLength() > limit) {
        quill.deleteText(limit, quill.getLength());
      }
    });
    this.setState({
      detail: value,
    });
  }

at Render:

<ReactQuill
     ref={(el) => {
        this.reactQuillRef = el;
     }}
     onChange={this.handleDetailChange}
        value={this.state.detail || ""}
     >
     <p>{this.reactQuillRef.getLength() + "/950"}</p>
</ReactQuill>

Solution

  • 1)create a custom module and register it with qill as below.

        class Counter {
        constructor(quill, options) {
          this.quill = quill;
          this.options = options;
          this.container = document.querySelector(options.container);
          quill.on('text-change', this.update.bind(this));
          this.update();  // Account for initial contents
        }
    
        calculate() {
          let text = this.quill.getText().trim();
          if (this.options.unit === 'word') {
            text = text.trim();
            // Splitting empty text returns a non-empty array
            return text.length > 0 ? text.split(/\s+/).length : 0;
          } else {
            return text.length;
          }
        }
    
        update() {
          var length = this.calculate();
          var label = this.options.unit;
          if (length !== 1) {
            label += 's';
          }
          this.container.innerText = length + ' ' + label;
        }
      }
     Quill.register('modules/counter', Counter);
    

    2) then add below code to modules as shown in image.

    counter: {
        container: '#counter',
        unit: 'character'
      }
    

    enter image description here

    3) now you can add a new div tag under quilleditor tag with counter id.

    <ReactQuill
         ref={(el) => {
            this.reactQuillRef = el;
         }}
         onChange={this.handleDetailChange}
            value={this.state.detail || ""}
         >
         <p>{this.reactQuillRef.getLength() + "/950"}</p>
    </ReactQuill>
    <div id="counter">0</div>
    

    enter image description here