Slate Example
A simple example showing how to use Slate in a JSFiddle.
HTML
<script src="https://npmcdn.com/react/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom/dist/react-dom.js"></script>
<script src="https://npmcdn.com/immutable/dist/immutable.js"></script>
<script src="https://npmcdn.com/slate/dist/slate.js"></script>
<div id="main"></div>
Babel + JSX
const { Editor, Raw } = Slate
const DEFAULT_NODE = 'paragraph'
const schema = {
nodes: {
'h1': props => <h1 {...props.attributes}>{props.children}</h1>
}
}
class MyEditor extends React.Component {
state = {
state: Raw.deserialize({ nodes: [
{
'kind': 'block',
'type': 'paragraph',
'nodes': [
{
'kind': 'text',
'ranges': []
}
]
}
] }, { terse: true })
};
hasBlock = (type) => {
const { state } = this.state
return state.blocks.some(node => node.type == type)
}
onChange = (state) => {
console.log("onChange~")
this.setState({ state })
}
onDocumentChange = (document, state) => {
console.log("Yay, the document changed!");
}
onClickBlock = (e, type) => {
e.preventDefault()
const isActive = this.hasBlock(type)
console.log(isActive ? DEFAULT_NODE : type)
this.setBlock(isActive ? DEFAULT_NODE : type)
}
setBlock = (type) => {
const currentState = this.state.state;
const state = currentState
.transform()
.setBlock(type)
.focus()
.apply()
this.setState({ state: state })
}
onSelectChange = (event) => {
event.preventDefault()
const type = event.target.value
this.setBlock(type)
}
render = () => {
return (
<div>
{this.renderToolbar()}
<hr/>
{this.renderEditor()}
</div>
)
}
renderToolbar = () => {
return (
<div className="menu toolbar-menu">
{this.renderBlockButton('h1', 'Toggle Heading')}
</div>
)
}
renderBlockButton = (type, text) => {
const isActive = this.hasBlock(type)
const onMouseDown = e => this.onClickBlock(e, type)
return (
<span className="button" onMouseDown={onMouseDown} data-active={isActive}>
<button>{text}</button>
</span>
)
}
renderEditor = () => {
return (
<div className="editor">
<Editor
placeholder={'Look,...