Search code examples
reactjswysiwygdraftjs

React Draft Wysiwyg apply bold, italic or udenderlina to whole content


I need to apply the Bold, Italic, Underline style to the whole content of editor, without selected text, like the align styles but I couldn't find the way for that. Is the possible to change the action or handler?


Solution

  • Yes, it is possible. You could update your SelectionState at the moment where your applying style. Here, we selecting all text

    const selection = editorState.getSelection().merge({
      anchorKey: currentContent.getFirstBlock().getKey(),
      anchorOffset: 0,
      focusOffset: currentContent.getLastBlock().getText().length,
      focusKey: currentContent.getLastBlock().getKey()
    });
    

    Then, we applying new selection

    const editorStateWithAllSelection = EditorState.acceptSelection(
      editorState,
      selection
    );
    
    const newState = RichUtils.toggleInlineStyle(
      editorStateWithAllSelection,
      inlineStyle
    )
    

    if you want to avoid your text to be selected in the end result, we could apply our old selection

    const selectionBefore = editorState.getSelection();
    
    // updating selection, toggling style ...
    
    const editorStateWithSelectionBefore = EditorState.acceptSelection(
      newState,
      selectionBefore
    );
    
    setEditorState(editorStateWithSelectionBefore);
    

    Example on Codeandbox