Slate Example
A simple example showing how to use Slate in a JSFiddle.
HTML
<script src="https://npmcdn.com/react@16.0.0/umd/react.development.js"></script>
<script src="https://npmcdn.com/react-dom@16.0.0/umd/react-dom.development.js"></script>
<script src="https://npmcdn.com/immutable/dist/immutable.js"></script>
<script src="https://npmcdn.com/slate/dist/slate.js"></script>
<script src="https://npmcdn.com/slate-base64-serializer/dist/slate-base64-serializer.js"></script>
<script src="https://npmcdn.com/slate-html-serializer/dist/slate-html-serializer.js"></script>
<script src="https://npmcdn.com/slate-hyperscript/dist/slate-hyperscript.js"></script>
<script src="https://npmcdn.com/slate-plain-serializer/dist/slate-plain-serializer.js"></script>
<script src="https://npmcdn.com/slate-prop-types/dist/slate-prop-types.js"></script>
<script src="https://npmcdn.com/slate-react/dist/slate-react.js"></script>
<script src="https://npmcdn.com/slate-simulator/dist/slate-simulator.js"></script>
<div id="main"></div>
Babel + JSX
// The packages & plugins are exposed as globals...
const Html = window.SlateHtmlSerializer.default
const Editor = window.SlateReact.default
const html = new Html({
rules: [{
deserialize(el, next) {
if (el.tagName.toLowerCase() === 'p') {
return {
kind: 'block',
type: 'paragraph',
data: {},
nodes: next(el.childNodes)
}
}
if (el.tagName.toLowerCase() === 'a') {
return {
kind: 'inline',
type: 'link',
data: {
href: el.getAttribute('href')
},
nodes: next(el.childNodes)
}
}
if (el.tagName.toLowerCase() === 'sup') {
return {
kind: 'inline',
type: 'footnote',
data: {
href: el.getAttribute('href')
},
nodes: next(el.childNodes)
}
}
}
}]
})
class MyEditor extends React.Component {
constructor(props) {
super(props)
this.state = {
state: html.deserialize(`
<p>A bit of content in a Slate editor.<p><p>A bit of content in a Slate editor.<sup title="http://example.com">1</sup></p><p>abcede</p>`)
}
}
onChange({ state }) {
this.setState({ state })
}
renderNode = (props) => {
const { attributes, children, node } = props
switch (node.type) {
case 'paragraph': return <p {...attributes}>{children}</p>
case 'footnote': return <sup {...attributes} title={node.data.get('title')}>{children}</sup>
case 'link': return <a href={node.data.get('href')} {...attributes}>{children}</a>
}
}
render() {
return (
<Editor
placeholder="Enter some text..."
onChange={change => this.onChange(change)}
renderNode={this.renderNode}
state={this.state.state}
/>
)
}
}
ReactDOM.render(<MyEditor />, document.getElementById('main'))