Search code examples
javascriptreactjsquill

Getting values from a text editor in React js


I'm using a quill js component (a text editor) for Reactjs and I'm testing it to see all it's features.

I managed to build a editor with a toolbar, but now I have a doubt, how can I get everything the user typed and save it in my state? As I'll show you in the code if I console.log(the quillRef.current) I get a div and way inside it I have a p element which contains everything the user has typed. My idea is to place a button in the end, and when the user stops typing and clicks the button I store what they typed.

here's a link to the sandbox where I'm testing it: codesandbox link


Solution

  • With quill.getText() function :

    import React, { useState } from "react";
    
    import { useQuill } from "react-quilljs";
    
    export default () => {
      const { quill, quillRef } = useQuill();
      const [savedText, setSavedText] = useState("");
    
      const handleSave = () => {
        const text = quill.getText();
        setSavedText(text);
      };
    
    
      return (
        <div style={{ width: 500, height: 300 }}>
          <button onClick={handleSave}>SAVE</button>
          <div>Saved State : {savedText}</div>
          <div ref={quillRef} />
        </div>
      );
    };
    

    Check on codesandbox : https://codesandbox.io/s/react-quilljsbasic-tt6pm?file=/src/App.js