How to get content from Quilljs in React

How to read content from Quilljs Editor in React


Using react-quilljs we can add a RichText Editor in to our web application (Reactjs). How do we get the contents/state ?

We can use the quill object return by the hook to access the state.

  const { quill, quillRef } = useQuill(); 

Trying to access the data directly ends up with error. We need useEffect hook to keep track of the content.

  React.useEffect(() => {
    if (quill) {
      quill.on("text-change", (delta, oldDelta, source) => {
        console.log("Text change!");
        console.log(quill.getText()); // Get text only
        console.log(quill.getContents()); // Get delta contents
        console.log(quill.root.innerHTML); // Get innerHTML using quill
        console.log(quillRef.current.firstChild.innerHTML); // Get innerHTML using quillRef
      });
    }
  }, [quill]);

Now we can us the quill on method for track changes through a function as above. For getting Text only we can use getText() method, for entire object delta we require getContents() and for HTML can rely on innerHTML.

See the CodesandBox for a live example

Create a RichText editor using Quilljs

How to use Quill toolkit in React


Quilljs is a Javascript editor for enriching the web applications. The toolkit was used by companies like, LinkedIn, Slab etc.

How to use Quill in React

For React we can use community libraries such as react-quilljs. Let’s setup a React project and install the dependencies.

npx create-react-app myapp
yarn add react-quilljs quill

We can use the the useQuill hook implement the toolkit as follows.

import React from 'react';
import { useQuill } from "react-quilljs";
  
 

export default function Editor() {
    const { quill, quillRef } = useQuill();
  return (
    <div style={{ width: 1000, height: 300 }}>
      <div ref={quillRef} />
     
    </div>
  )
}

The styling (CSS) may not work properly, for that import the CSS class provided by Quill.

 import "quill/dist/quill.snow.css";  

A live version of the project can be found at sandbox , in case required.

Links

React-Quills