Search code examples
javascriptreactjsautocompleteeditordraftjs

How to use replaceWithFragment in draft-js?


I need to replace "prefix" what user type for autocomplete text. In docs I found that, but I really don't know how to use this.

replaceWithFragment(
  contentState: ContentState,
  targetRange: SelectionState,
  fragment: BlockMap
): ContentState

I tried to type this solution, but how I explain before I got selection with some "prefix" from user.

Eg.when I type "SEL" my autocomplete find for me "SELECT" I will click on that suggestion and in editor I got "SELSELECT".

suggestionSelected(value){
        const { editorState } = this.state;
        const pastedBlocks = ContentState.createFromText(value).blockMap; //get blockMap
        const newState = Modifier.replaceWithFragment( //replaceWithFragment -> set new state editor
            editorState.getCurrentContent(),
            editorState.getSelection(),
            pastedBlocks
          );
            this.setState(() => ({
                suggestion: [],
                 editorState: EditorState.push(editorState, newState, 'insert-fragment')//Insert suggestion with "prefix"



            }));

        }//End of suggestionSelected

Eg.when I type "SEL" my autocomplete find for me "SELECT" I will click on that suggestion and in editor I got "SELSELECT".


Solution

  • I created a method for it.... Dunno how to work with draft....

     gettingSuggestion = (str, str2) =>{
    
                let remain ="";
    
                str = str.toUpperCase();//for compare
                for( let i = 0 ; i<str2.length ; i++){
                    if(str2[i]!==str[i]){ //if not equal -> we are searching for remaining characters
                      remain= remain.concat(str2[i]);//remain + suggestion
                    }
                }
                return(remain);
            }
    suggestionSelected(value){
            const { editorState } = this.state;
    
            const values =this.value.split(" ");//for up to date values
            const remainer = this.gettingSuggestion(values[this.index], value);//remaining values
    
            const pastedBlocks = ContentState.createFromText(remainer).blockMap; //get blockMap
            const newState = Modifier.replaceWithFragment( //replaceWithFragment -> set new state editor
                editorState.getCurrentContent(),//ContentState
                editorState.getSelection(),//SelectionState
                pastedBlocks//BlockMap
    
              );        
    
                this.setState(() => ({
                    suggestion: [],
                     editorState: EditorState.push(editorState, newState, 'insert-fragment')//Inserting values 
    
                }));
    
            }//End of suggestionSelected