Search code examples
reactjsrich-text-editorslate.js

How to set slate value based on the plain string value(serialized)


I am building a rich text editor with slate js on React and I need to parse URL from the content(for example: www.website.me should be transformed to www.website.me).

I have already implemented the function to parse URL from plain text and then wrap the content inside the correct tag.

However, the problem is that I need to display the parsed value as soon as the user is typing on the editor(on onChange event). Here is what I have :

onChange = ({ value }) => {
    const { isFocused } = value.selection
    if (isFocused !== this.state.isFocused) {
      this.setState({ isFocused })
    }

    const string = this.state.html.serialize(value)
    const linkifiedString = linkifyHtml(string) || ''
    if (value.document !== this.state.value.document) {
      const { onChange } = this.props
      onChange && onChange(linkifiedString)
    }

    // this won't work and will call the onChange method infinitely
    this.setState({ value: this.state.html.deserialize(linkifiedString) })
}

Thanks for your help.


Solution

  • Finally, I have found the solution, you have to create your own slate plugin or use this one: https://github.com/enzoferey/slate-instant-replace