5

I'm trying to implement a button that changes inline-style to bold after clicking on it. I want to implement this example but using React Hooks.

After clicking on the button, RichUtils is executing but it's not changing the text to bold. What I'm missing?

import React, { useEffect, useRef, useState } from 'react';
import {Editor, EditorState, RichUtils}       from 'draft-js';

const MyEditor = () => {

    const [editorState, setEditorState] = useState(EditorState.createEmpty());
    const editor                        = useRef(null);

    const focusEditor = () => {

        editor.current.focus();

    }

    const boldText = () => {

        let nextState = RichUtils.toggleInlineStyle(editorState, 'BOLD');

        setEditorState(nextState);

    }

    return (
        <div onClick = {focusEditor}>
            <button onClick = { () => boldText()}>Bold</button>
            <Editor
                ref = {editor}
                editorState = {editorState}
                onChange = {editorState => setEditorState(editorState)}
            />
        </div>
    );
}

export default MyEditor;
Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36

1 Answers1

4

It isn't overtly clear to me why, but your focus function seems to interrupt the bold toggling. Removing it allowed the toggling to function the same as the example you linked to.

const MyEditorFunctional = () => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());

  const boldText = () => {
    const nextState = RichUtils.toggleInlineStyle(editorState, "BOLD");

    setEditorState(nextState);
  };

  return (
    <div>
      <button type="button" onClick={boldText}>
        Bold
      </button>
      <Editor
        editorState={editorState}
        onChange={setEditorState}
      />
    </div>
  );
};

Edit sharp-brattain-cx97c

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 4
    Thanks for the answer, Drew. I was going crazy. There is one more issue though, Editor is losing focus by clicking on the button, even by adding e.preventDefault() in the boldText() function. The solution is instead of using 'onClick', using 'onMouseDown'. Then everything works as expected. – Erik Martín Jordán Feb 26 '20 at 04:49