diff --git a/docs/src/demos/React/components/Editor.js b/docs/src/demos/React/components/Editor.js new file mode 100644 index 00000000..6c4992de --- /dev/null +++ b/docs/src/demos/React/components/Editor.js @@ -0,0 +1,30 @@ +import React, { useState, useRef, useEffect, createContext, useContext } from 'react' +import { Editor as Tiptap } from '@tiptap/core' + +export const EditorContext = createContext({}) + +export const useEditor = () => useContext(EditorContext) + +export const Editor = ({ value, onChange, children, ...props }) => { + const [editor, setEditor] = useState(null) + const editorRef = useRef(null) + + useEffect(() => { + const e = new Tiptap({ + element: editorRef.current, + content: value, + ...props, + }).on('transaction', () => { + onChange(e.json()) + }) + + setEditor(e) + }, []) + + return ( + + {editorRef.current && children} +
+ + ) +} diff --git a/docs/src/demos/React/index.jsx b/docs/src/demos/React/index.jsx index cd6160dd..630a3d56 100644 --- a/docs/src/demos/React/index.jsx +++ b/docs/src/demos/React/index.jsx @@ -1,40 +1,69 @@ -import React, { Component } from 'react' -import { Editor } from '@tiptap/core' +import React, { useState } from 'react' +import { useEditor, Editor } from './components/Editor' import extensions from '@tiptap/starter-kit' -export default class extends Component { - constructor() { - super() - this.editorNode = React.createRef() - } - - componentDidMount() { - this.editor = new Editor({ - element: this.editorNode.current, - content: '

rendered in react!

', - extensions: extensions(), - }) - this.forceUpdate() - } +// Menu bar example component +// useEditor only works for child components of +const MenuBar = () => { + const editor = useEditor() - render() { - return ( -
- {this.editor && -
- - -
- } -
-
- ) - } + return ( + <> + + + + ) +} + +export default () => { + const [value, setValue] = useState({ + 'type': 'document', + 'content': [ + { + 'type': 'paragraph', + 'content': [ + { + 'type': 'text', + 'text': 'rendered in ' + }, + { + 'type': 'text', + 'marks': [ + { + 'type': 'bold' + } + ], + 'text': 'react' + }, + { + 'type': 'text', + 'text': '!' + } + ] + } + ] + }) + + return ( + <> +

+ +

+
+ + + + + ) }