Slate JS: set the prop as the Editor's value

5k views Asked by At

I am building an textarea email form using Slate JS editor. Instead of slate default initial state value, I would like to display my own value which is passed to the component as a prop from redux.

So instead of this:

        <Editor
    spellCheck
    autoFocus
    placeholder="Enter your text..."
    ref={this.ref}
    **value = {this.state.value}**
    onPaste={this.onPaste}
    onChange={this.onChange}
    renderNode={this.renderNode}
    renderMark={this.renderMark}
    />

I am doing this:

        <Editor
    spellCheck
    autoFocus
    placeholder="Enter your text..."
    ref={this.ref}
    **value = {Value.fromJSON(JSON.stringify(this.props.richText))}**
    onPaste={this.onPaste}
    onChange={this.onChange}
    renderNode={this.renderNode}
    renderMark={this.renderMark}
    />

So that prop is passed as an object, converted first to json and then to required slate editor format. That doesn't break the component but the value is not displayed in the editor. What am I doing wrong and what is the right way to set up the slate editor value as a prop? Thank you for any help with this!

1

There are 1 answers

0
Mark Allen On

The value in Slate is much more than just the value of a text field, and basically stores all the data about the Slate editor.

To pass in data from props, you need to deserialize this.props.richText and store it in state, and then update state's value every time Editor changes. Here's how you'd do that if you want a plain text editor.

import { Editor } from 'slate-react'
import Plain from 'slate-plain-serializer'
​
class App extends React.Component {
  state = {
    value: Plain.deserialize(this.props.richText),
  }
​
  onChange = ({ value }) => {
    this.setState({ value })
  }
​
  render() {
    return <Editor value={this.state.value} onChange={this.onChange} />
  }
}

If you want a rich text or html editor, the deserialization is a little more involved, but pretty straightforward if you follow these guides: