reactjswysiwygdraftjsreact-draft-wysiwyg

change the react-draft-wysiwyg code from class component to functional component


heloo guys can you help me to change the react-draft-wysiwyg code from class component to functional component?
cause i'm not familiar with class component,please help me!

import React, { Component } from "react";
import { EditorState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

class NewEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty(),
      uploadedImages: [],
    };
    this._uploadImageCallBack = this._uploadImageCallBack.bind(this);

  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  _uploadImageCallBack(file) {
    let uploadedImages = this.state.uploadedImages;
    const imageObject = {
      file: file,
      localSrc: URL.createObjectURL(file),
    };
    uploadedImages.push(imageObject);
    this.setState({ uploadedImages: uploadedImages });
    return new Promise((resolve, reject) => {
      resolve({ data: { link: imageObject.localSrc } });
    });
  }

  render() {
    const { editorState } = this.state;
    

  

Solution

  • It is pretty straightforward, although you omitted the render method of your class component.

    Basically, we convert this.state, to React.useState(). Then update _uploadImageCallback to be an async function.

    import React, { useState } from 'react';
    
    const NewEditor = (props) => {
      const [editorState, setEditorState] = useState(EditorState.createEmpty());
      const [uploadedImages, setUploadedImages] = useState([])
    
      const onEditorStateChange = (editorState) => {
        setEditorState(editorState)
      };
    
      const _uploadImageCallBack = async (file) => {
        const imageObject = {
          file: file,
          localSrc: URL.createObjectURL(file),
        };
    
        setUploadedImages([...uploadedImages, imageObject]);
    
        return { data: { link: imageObject.localSrc } };
      };
    
      return <></>;
    };