Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple variable placeholders in Draft.js

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?

like image 615
keoghpe Avatar asked Dec 06 '25 18:12

keoghpe


1 Answers

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.

like image 188
KRRISH96 Avatar answered Dec 09 '25 15:12

KRRISH96



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!