Retrieve a string from an EditorBlock within a custom ComponentBlock with React and Draft.js

  draftjs, editor, image, javascript, reactjs

I am trying to build a custom Draft.js ComponentBlock to accept an image URL in order to display an image within the Editor component. I tried using an tag and a "useState" hook, updated via a function onChange, that could store the input tag’s value until the user was done typing/pasting the URL. However, the input tag was unusable because the text written in the input field would not appear in the input field, but would be stored in the EditorState until about 5 characters into typing, and pasting wouldn’t display at all. I did some looking and found this:

https://draftjs.org/docs/advanced-topics-block-components/

which suggests using an "EditorBlock" component instead. However, while on the screen the component displays text just fine, I’m struggling to find a way to retrieve the data that is entered into the EditorBlock component. See in the code below.

Thank you!

import React, {useState} from 'react';
import { EditorBlock } from 'draft-js';

export function ImageButton(props){

    const [ imageURL, setImageURL ] = useState("");
    const [ insertURL, setInsertURL ] = useState("");
    
    console.log(insertURL);

    function handleSelect(){
        setImageURL(insertURL)
    }

    if(imageURL == ""){
        return(
            <div>
                <p>Insert URL:</p>
                {/* <input
                    value={insertURL}
                    onChange={(evt) => {handleInputChange(evt, setInsertURL)}}
                /> */}
                <div>
                    <EditorBlock {...props} onChange={(env) => setInsertURL(env.target.value)}/>
                </div>
                
                <button onClick={handleSelect}>Select</button>
            </div>
        )
    }
    else{
        return(
            <div>
                <img src={imageURL} />
            </div>
        )
    }
}

Source: Ask Javascript Questions

LEAVE A COMMENT