0

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.

Faisal Mq
  • 5,036
  • 4
  • 35
  • 39
  • you must clear the things you want to replace #. because the really difficult part is dealing html nodes with draft. – Jiang YD Sep 02 '16 at 03:59
  • 1
    Problem is that DraftJS is lacking examples for its Modifier commands in particular. The Examples folder only includes very basic ones like bold, italic, linking etc. – Faisal Mq Sep 02 '16 at 05:54
  • Yes because draft is not designed to edit html, but to editor texts with decorators. Other things beside text only can be managed as a `atomic` block. – Jiang YD Sep 02 '16 at 07:14

1 Answers1

2

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 ): ContentState

Replaces 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.

Carmon
  • 59
  • 5