Skip to content

Conversation

dmc31a42
Copy link

Export react context to use class component like Class.contextType or Context.Consumer

Class.contextType

https://ko.reactjs.org/docs/context.html#contextconsumer

class MyClass extends React.Component {
  static editorView = EditorViewContext;
  onClick = () => {
      const view = this.context;
      if (!view) return;
      ...
      const tr = view.state.tr.replaceWith(selection.from, selection.to, node);
      view.dispatch(tr);
  }

  render() {
    ...
  }
}

Context.Consumer

https://ko.reactjs.org/docs/context.html#contextconsumer

class MyClass extends React.Component {
  onClick = (state: EditorState<typeof schema> | null, dispatch?: ((tr: Transaction) => void) | undefined, view?: EditorView<typeof schema> | null) => {
    if (!view) return;
   ...
    const tr = view?.state.tr.replaceWith(selection.from, selection.to, node);
    view.dispatch(tr);
  }

  render() {
    return (
    <EditorProvider
        schema={schema}
        plugins={plugins}
        doc={this.props.initialDoc}
      >
        <Editor />
        <EditorStateContext.Consumer>
          {(state) => 
           <EditorViewContext.Consumer>
             {(view) => (
               <button onClick={() => this.onClick(state, view?.dispatch, view)}>Button</button>
             )}
           </EditorViewContext.Consumer>
          }
        </EditorStateContext.Consumer>
      </EditorProvider>
    )
  }    

…or `Context.Consumer`

(cherry picked from commit bef197b)
@hubgit hubgit closed this Aug 13, 2025
@hubgit hubgit reopened this Aug 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants