Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda