Draft-js: How to add onFocus and onBlur event in Draft-js Editor ?

Created on 11 Dec 2017  路  3Comments  路  Source: facebook/draft-js

Can you give me an example for How to use onFocus and onBlue functional events with draft-js.

All 3 comments

@mvnn just add event handlers as props:

<Editor onBlur={...} onFocus={...} />

More info in the docs: https://draftjs.org/docs/api-reference-editor.html#mouse-events

Also btw - please join the draft js community on slack for more immediate help: https://draftjs.herokuapp.com

The mentioned link https://draftjs.org/docs/api-reference-editor.html#mouse-events is not to be found anymore. On the other hand, as of version 0.11.6 the callbacks passed to onFocus and onBlur are never invoked even though the draft state updates seamlessly. Consider the following:

import {
  ContentState,
  Editor,
  EditorState,
  EditorProps,
} from 'draft-js';
import React from 'react';

export const MyEditor: React.FC<
  { text: string } & Omit<EditorProps, 'editorState' | 'onChange'>
> = ({ text, ...props }) => {
  const [editorState, setEditorState] = React.useState(
    EditorState.createWithContent(ContentState.createFromText(text)),
  );

  const editor = React.useRef<Editor>(null);

  function focusEditor() {
    editor.current?.focus();
  }

  return (
    <div onClick={focusEditor}>
      <Editor
        ref={editor}
        editorState={editorState}
        onChange={(editorState) => setEditorState(editorState)}
        {...props}
        onFocus={console.log} // * never invoked
        onBlur={console.log} // * never invoked
      />
    </div>
  );
};

EDIT

The reason why reason why the callbacks aren't invoked is because of StrictMode, although it appears that the issue is tied to the react version namely ^0.0.0-experimental-33c3af284. To illustrate further:

// Does not work
ReactDOM.render(
  <React.StrictMode>
    <Editor text={'Test'} />
  </React.StrictMode>,
  document.getElementById('root'),
);
// Works
ReactDOM.render(
    <Editor text={'Test'} />,
  document.getElementById('root'),
);

In the end I ended up upgrading react and react-dom with yarn add react@latest react-dom@latest

Was this page helpful?
0 / 5 - 0 ratings