How to insert gifs in slate editor

86 views Asked by At

I have a slate text editor in my app and would like to insert gifs with the use of giphy links. I'm attempting to add with the use of the insertNodes function but that seems to just add a new line. I've listed the function I'm using to add the gif below;

  function insertImage(editor, url) {
    const element = { type: 'video', url, children: [{ text: '' }] }
    Transforms.insertNodes(editor, element)
  }

I'm just using a publicly available gif link to make sure I can actually add gifs into the editor. So I'm certain that the link or anything else is not the issue. I've also attempted this with links from other places with no luck so I'd appreciate any input on this.

Also adding my render element function below;

const renderElement = useCallback((props) => <Element {...props} />, []);

and finally my element definition;

const Element = ({ attributes, children, element }) => {
  const style = { textAlign: element.align }
  switch (element.type) {
    case "block-quote":
      return (
        <blockquote style={style} {...attributes}>
          {children}
        </blockquote>
      )
    case "bulleted-list":
      return (
        <ul style={style} {...attributes}>
          {children}
        </ul>
      )
    case "heading-one":
      return (
        <h1 style={style} {...attributes}>
          {children}
        </h1>
      )
    case "heading-two":
      return (
        <h2 style={style} {...attributes}>
          {children}
        </h2>
      )
    case "list-item":
      return (
        <li style={style} {...attributes}>
          {children}
        </li>
      )
    case "numbered-list":
      return (
        <ol style={style} {...attributes}>
          {children}
        </ol>
      )
    default:
      return (
        <p style={style} {...attributes}>
          {children}
        </p>
      )
  }
}
1

There are 1 answers

0
Mark Barton On

According to the slate docs: https://docs.slatejs.org/walkthroughs/03-defining-custom-elements

And also this SO post: How to align text in Slate.js and React?

You need to modify your renderElement callback to display different components based on a certain modifier. For example, if you are using a code element and you wish to display this in the Editor, usually you will give your Slate node a type property with the value of code. Then in your renderElement function, the props you are passing contains the type that is to be rendered.

So for your use case, you would do something like the following;

const renderElement = useCallback({ attributes, children, element }) => {
    switch (element.type) {
        case 'video':
        return (
            <div {...attributes} className='video-wrapper'>
                <video src={element.url} className='video' />
            </div>
        )
        default:
        return (
            <p {...attributes}>
                {children}
            </p>
        )
    }