Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
Draft JS programmatically insert text as span

I am using Draft.js for its mentions plugin. Sometimes, I want users to add a mention not by selecting an item from a dropdown but by writing something like, for example, "@item" or "@item".

As you can see in the function below, if I type a word that starts with @* or ends with * it becomes a mention automatically.

export const replaceString = (editorState, setEditorState) => {
    const contentState = editorState.getCurrentContent();
    const selectionState = editorState.getSelection();
    const block = contentState.getBlockForKey(selectionState.getAnchorKey());

    const blockAsArray = block.getText().split(' ');
    const lastWord = blockAsArray.pop();
    if (lastWord.startsWith('@*') || lastWord.endsWith('*') ) {
        const currentSelectionState = editorState.getSelection();
        const currentContent = editorState.getCurrentContent();
        const contentStateWithEntity = currentContent.createEntity(
            "MENTION",
            "MUTABLE",
            { nature: 'remedy', lastWord}
        );

        const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
        const newContentState = Modifier.replaceText(
            contentState,
            selectionState.merge({
                anchorOffset: currentSelectionState.getEndOffset() - lastWord.length,
                focusOffset: currentSelectionState.getEndOffset()
            }),
            lastWord,
            editorState.getCurrentInlineStyle(),
            entityKey
        );

        setEditorState(EditorState.push(
            editorState,
            newContentState,
            'replace-text'
        ))
    } else {
        setEditorState(editorState)
    }
}

What I would love to do now is to insert this mention as a span that I can style. Is there a way I can do that?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

https://draftjs.org/docs/advanced-topics-inline-styles/

Draftjs render to span from it's own model. You should control styles by entity.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!