How to use RichUtils with React Hooks

Viewed 1140

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;
1 Answers

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

Related