0

This is how the code looks like on the page

import { SyncOutlined, CameraFilled, LoadingOutlined } from "@ant-design/icons";
import React, { useState, useEffect, useRef } from "react";
import { Avatar } from "antd";
//import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import "react-quill/dist/quill.core.css";
import "react-quill/dist/quill.bubble.css";
import "quill-image-uploader/dist/quill.imageUploader.min.css";
import axios from "axios";
import dynamic from "next/dynamic";

const ReactQuill = dynamic(() => import("react-quill"), { ssr: false });
const Quill = dynamic(() => import("quill"), { ssr: false });

const CreatePostForm = ({
  postUpload,
  postSubmit,
  content,
  setContent,
  loading,
  handleImage2,
  placeholder,
  uploading,
  image,
}) => {

  const quillRef = useRef();

  const [image2, setImage2] = useState({});
  const [theme, setTheme] = useState("snow");
  const handleThemeChange = (newTheme) => {
    if (newTheme === "bubble") {
      -setTheme("bubble");
    }
    if (newTheme === "snow") {
      setTheme("snow");
    }
  };
  

  const imageHandler = () => {
    const input = document.createElement("input");

    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.click();
    console.log(input);
    console.log(new FormData());
    input.onChange = async (e) => {
      const file = e.target.files[0];
      //console.log(file);
      const formData = new FormData();
      console.log([...formData]);
      formData.append("image", file);
      console.log([...formData]);
      
      const quill = quillRef.current.getEditor();
      console.log(quill);
      const range = quill.getSelection(true);

      // Insert temporary loading placeholder image
      quill.insertEmbed(
        range.index,
        "image",
        `${window.location.origin}/images/loaders/placeholder.gif`
      );

      // Move cursor to right side of image (easier to continue typing)
      quill.setSelection(range.index + 1);
      try {
        const { data } = await axios.post("/uploadImage", formData);
        if (data.error) {
          toast.error(data.error);
        }
        console.log("uploaded image=>", data);
        setImage2({
          url: data.url,
          public_id: data.public_id,
        });
        quill.deleteText(range.index, 1);

        // Insert uploaded image
        
        quill.insertEmbed(range.index, "image", data.url);
        console.log(quill);
      } catch (err) {
        console.log(err);
      }
      
    };
  };
  let modules = {
    toolbar: {
      container: [
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        ["bold", "italic", "underline"],
        [{ font: [] }],
        [{ size: [] }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ align: [] }],
        [
          "link",
          "image", "video"
        ],
        ["clean"],
        [{ color: [] }],
      ],
       handlers: {
         image: imageHandler,
       },
    },
  };
  const formats = [
    "header",
    "font",
    "size",
    "bold",
    "italic",
    "underline",
    "strike",
    "blockquote",
    "list",
    "bullet",
    "indent",
    "link",
    "image",
    "video",
  ];


  return (
    <div className="card ">
      <div className="card-body">
        <form className="form-group" onSubmit={postSubmit}>
          <hr />
          <ReactQuill
            ref={quillRef}
            value={content}
            onChange={(e) => setContent(e)}
            className="form-control"
            theme={"snow"}
            placeholder="Write Something..."
            modules={modules}
            formats={formats}
            preserveWhitespace={true}
          />
  

          
          <div className="card-footer d-flex  text-muted">
            <label className=" justify-content-left m-2 py-2">
              {image && image.url ? (
                <Avatar size={30} src={image.url} className="mt-1" />
              ) : uploading ? (
                <LoadingOutlined className="size py-2" />
              ) : (
                <CameraFilled className="size py-2" />
              )}

              <input
                type="File"
                className=" m-2 py-2"
                accept="images/*"
                onChange={handleImage2}
                hidden
              />
            </label>
            <div className="justify-content-end">
              <button
                onClick={postUpload}
                className="btn-lg btn btn-success py-2 m-2"
              >
                RESET
              </button>

              {/*  */}

              <button
                disabled={!content && !image}
                className="btn-lg btn btn-success py-2 m-2"
                type="submit"
                onClick={postSubmit}
              >
                {loading ? <SyncOutlined spin className="py-1" /> : "POST"}
              </button>
            </div>
          </div>
        </form>
      </div>
      <script src="/dist/quill.js"></script>
      <script src="/dist/quill.imageUploader.min.js"></script>
    </div>
  );
};
export default CreatePostForm;

One error I am getting in this code while initiating the range. How do I define quillRef which is an reference instance of the ReactQuill. I have searched the solution in chatgpt or bard too but none of them seems to be working

I am trying to add a image handler to the image icon on ReactQuill toolbar so that while I click the image icon on the toolbar and while selecting and opening an image the image can be uploaded to the server which is defined at the endpoint and render the image from the response url in the editor where cursor points.

  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community May 20 '23 at 12:12

0 Answers0