Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda