Reputation: 5534
I am using DraftJS Editor for having Rich Text features in my application's React based web page.
I have the following requirement:
When a user types in # key, a drop down is displayed besides Editor, from where user can choose an option. Depending upon his choice I want to replace # with some HTML, example an image.
I have created logic for showing drop down as soon as user types in # character in the Editor but do not understand how to replace that hash character then with some other HTML/text.
I have googled for finding on how to do this but not able to find so far, one such precise example on this.
Can someone guide on this, better with some example?
Note: I know that there are some DraftJS plugins that provide mentions sort of functionality, but I don't want to use those, rather just want to go on with my own logic using the content replacement thing I mentioned above.
Upvotes: 0
Views: 6397
Reputation: 59
The replaceText
static method of Modifier
from Draftjs should accomplish what you're looking for: https://draftjs.org/docs/api-reference-modifier#replacetext
replaceText
replaceText( contentState: ContentState, rangeToReplace: SelectionState, text: string, inlineStyle?: DraftInlineStyle,
entityKey?: ?string ): ContentStateReplaces the specified range of this ContentState with the supplied string, with the inline style and entity key applied to the entire inserted string.
Example: On Facebook, when replacing @abraham lincoln with a mention of Abraham Lincoln, the entire old range is the target to replace and the mention entity should be applied to the inserted string.
If you want to add HTML string directly, you can't do it on the editor, you must use a combination of draftjs entities and a blockRendererFn to render the draftjs entities that you create as a HTML/reactjs component.
Upvotes: 2