Files
tiptap/demos/src/GuideContent/ExportJSON/React/index.jsx
2021-11-16 19:11:45 +01:00

97 lines
2.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useState, useEffect, useCallback } from 'react'
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import './styles.scss'
export default () => {
const [json, setJson] = useState(null)
const editor = useEditor({
content: `
<p>
Wow, this editor instance exports its content as JSON.
</p>
`,
extensions: [StarterKit],
})
useEffect(() => {
if (!editor) {
return null
}
// Get the initial content …
setJson(editor.getJSON())
// … and get the content after every change.
editor.on('update', () => {
setJson(editor.getJSON())
})
}, [editor])
const setContent = useCallback(() => {
// You can pass a JSON document to the editor.
editor.commands.setContent(
{
type: 'doc',
content: [
{
type: 'paragraph',
content: [
{
type: 'text',
text: 'Its 19871. You cant turn on a radio, or go to a mall without hearing Olivia Newton-Johns hit song, Physical.',
},
],
},
],
},
true,
)
// Its likely that youd like to focus the Editor after most commands.
editor.commands.focus()
}, [editor])
const clearContent = useCallback(() => {
editor.chain().clearContent(true).focus().run()
}, [editor])
if (!editor) {
return null
}
return (
<>
<div className="actions">
<button className="button" onClick={setContent}>
Set Content
</button>
<button className="button" onClick={clearContent}>
Clear Content
</button>
<button
onClick={() => editor.chain().focus().toggleBold().run()}
className={editor.isActive('bold') ? 'is-active' : ''}
>
Bold
</button>
<button
onClick={() => editor.chain().focus().toggleItalic().run()}
className={editor.isActive('italic') ? 'is-active' : ''}
>
Italic
</button>
</div>
<EditorContent editor={editor} />
<div className="export">
<h3>JSON</h3>
<pre>
<code>{JSON.stringify(json)}</code>
</pre>
</div>
</>
)
}