Monday, 7 August 2023

Custom image upload to Jodit editor

I need to change the process of uploading an image from computer to Jodit editor to React. I have already made several attempts to solve this problem, but none worked, this is because I did not understand how the customization of the Jodit uploader works. Here is my code without any failed attempts:

import JoditEditor from 'jodit-react'
import { useEffect, useRef } from 'react'

function JoditComponent({ article, updateArticle }) {
    const editorRef = useRef(null)

    useEffect(() => {
        console.log(article, updateArticle)
    }, [article, updateArticle])

    const config = {
        zIndex: 0,
        readonly: false,
        activeButtonsInReadOnly: ['source', 'fullsize', 'print', 'about'],
        toolbarButtonSize: 'middle',
        theme: 'default',
        enableDragAndDropFileToEditor: true,
        saveModeInCookie: false,
        spellcheck: true,
        editorCssClass: false,
        triggerChangeEvent: true,
        height: 450,
        direction: 'ltr',
        language: 'pt_BR',
        debugLanguage: false,
        i18n: 'en',
        tabIndex: -1,
        toolbar: true,
        enter: 'P',
        useSplitMode: false,
        colorPickerDefaultTab: 'background',
        imageDefaultWidth: 100,
        removeButtons: ['about', 'print', 'file'],
        disablePlugins: ['paste', 'stat'],
        events: {},
        textIcons: false,
        uploader: {},
        placeholder: '',
        showXPathInStatusbar: false,
    }

    return (
        <div>
            <JoditEditor
                id='article-content'
                value={article.content}
                ref={editorRef}
                config={config}
                tabIndex={1}
                onChange={(newContent) =>
                    updateArticle({
                        type: 'field',
                        field: 'content',
                        value: newContent,
                    })
                }
            />
        </div>
    )
}

export default JoditComponent

And here is the process that must be done to send the image to my backend: In the URL http://localhost:3000/files a post must be made with the image inside a formData. In the return of the request, if everything went well, there will be only one string inside the response data, this string is the URL of access to the image and must be this URL used in the image to be inserted in Jodit.

Here is a component where the user can choose an image from his computer and it is displayed on the screen (it is just an example):

import axios from 'axios'
import React, { useState } from 'react'

const Home = () => {
    const [selectedFile, setSelectedFile] = useState(null)
    const [imgUrl, setImgUrl] = useState(
        'https://st.depositphotos.com/1010338/2099/i/600/depositphotos_20999947-stock-photo-tropical-island-with-palms.jpg'
    )

    const handleFileChange = (event) => {
        setSelectedFile(event.target.files[0])
    }

    const handleUpload = () => {
        const formData = new FormData()
        formData.append('file', selectedFile)

        axios
            .post('http://localhost:3000/files', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            })
            .then((response) => {
                console.log(response)
                setImgUrl(response.data)
            })
            .catch((error) => {
                console.error(error)
            })
    }

    return (
        <>
            <div className='d-flex m-3'>
                <input
                    type='file'
                    onChange={handleFileChange}
                    className='form-control rounded-0 rounded-start'
                />
                <button
                    onClick={handleUpload}
                    className='btn btn-primary rounded-0 rounded-end'
                >
                    Enviar
                </button>
            </div>
            <img
                src={imgUrl}
                alt='Test'
                width={300}
            />
        </>
    )
}

export default Home


from Custom image upload to Jodit editor

No comments:

Post a Comment