Reputation: 404
We're trying to implement variable placeholders for a feature in our app.
Essentially the user will create a template using a WYSIWYG editor and put variables into the text e.g:
Hello {{first_name}}
These variables will then be interpolated by our back end (e.g. swapping {{first_name}} with "Peter").
Our users are non-technical so we don't want them to have to add the placeholders manually. We want them to drag and drop the variables into their text from a list that we predefine.
Is there a simple way of doing this with DraftJS or CKEdior out of the box?
Upvotes: 3
Views: 3965
Reputation: 657
Thanks for A2A.
We had a similar feature requirement to add templates with placeholders for mailing.
Dear {{recipient.first_name}},
Mail Body Template
With best regards,
{{sender.first_name}} {{sender.last_name}}
Manager - ABC Company.
Here is how we implemented it. I hope this would be helpful.
draft-js provides a Modifier class for this very use-case.
Modifier
API has insertText method to insert custom placeholder text in the content-{{first_name}}
in your case.
import { EditorState, Modifier } from 'draft-js';
insertPlaceholder = placeholderText => {
const { editorState } = this.state;
const newContentState = Modifier.insertText(
editorState.getCurrentContent(), // get ContentState from EditorState
editorState.getSelection(),
placeholderText
);
this.setState({
editorState: EditorState.createWithContent(newContentState); // get EditorState with ContentState
});
}
Then add a button to trigger the insertPlaceholder method.
<button
onClick={() => this.insertPlaceholder('{{first_name}}')}
>
Add First Name
</button>
When clicked on Add First Name
placeholder text will be inserted at the current cursor
position.
If the editor is out of focus, the text will be inserted at the beginning.
For Reusability, you can create a custom plugin and include it in options. Placeholder plugin example screenshot
Note:
If you have multiple placeholders, I would rather suggest using a select input
with possible placeholder options - this will keep UI clean instead of having a bunch of buttons.
Any suggestions are welcome.
Upvotes: 3
Reputation: 3934
You can create a button as follows
<button
onMouseDown={e => this.onAddText(e, '{{first_name}}' )}
>
ADD Name
</button>
and inside onAddText function
import { insertText } from 'draft-js-modifiers';
onAddText = (e, text) => {
e.preventDefault();
const { editorState } = this.state;
const EditorStat = insertText(editorState, text);
this.setState({ editorState: EditorStat });
};
insertText is method provided by draft-js-modifiers
and then use this.state.editorState as follows:
import {
Editor,
} from 'draft-js';
<Editor
editorState={this.state.editorState}
/>
Upvotes: 0