I am trying to implement a Custom decorator for my draft.js component. I do not want to use CompositeDecorator, because I would like to render possibly many different types of decorations based on the input. I could not find any documentation for DraftDecoratorType except type definitions in the draft.js repository - https://github.com/facebook/draft-js/blob/master/src/model/decorators/DraftDecoratorType.js
I took inspiration in https://github.com/SamyPesse/draft-js-prism/blob/master/lib/index.js and I decided to try with baby steps - just write a decorator that makes words starting with # bold.
The decorator I am using so far can be found below.
this.state = {
editorState: Draft.EditorState.createEmpty({
getComponentForKey(key: string): Function {
const originalText = key.split('.')[0];
return () => <b>{originalText}</b>;
},
getPropsForKey(key: string): any {
return {};
},
getDecorations(block: any, contentState: any): any {
const text = block.getText();
const decorations: Array<string | null> = Array(text.length).fill(null);
let counter = 0;
let result: RegExpExecArray;
const regex = /(^|\s)#\w+/g;
while ((result = regex.exec(text) as RegExpExecArray) != null) {
const start = result.index;
const end = start + result[0].length;
decorations.fill(result[0] + '.' + counter, start, end);
counter++;
}
console.log(decorations);
return Immutable.List(decorations);
}
})
};
full code of my component can be found at https://github.com/d-kozak/react-playground/blob/master/src/draftjs/CustomDecoratorExample.tsx
Unfortunately, the editor starts behaving unpredictably when I use it. At the moment, when I type in # followed by a character (eg #a), that is when the decorator is triggered, the text indeed becomes bold, but the focus is moved to the beginning of the text area and afterwards it just behaves very unpredictably. It is hard to describe, but you can actually try it yourself here: https://dkozak-react-playground.netlify.com
I have basically the same decorator implemented with CompositeDecorator at https://github.com/d-kozak/react-playground/blob/master/src/draftjs/CompositeDecoratorExample.tsx and it works as expected. If you open my netlify page, a live demo can be found on the other tab on the same page.
But something in my custom decorator is totally crashing the editor, but I am not sure why and how to fix it. Can someone please help me?