Render HTML directly into a component in Svelte 3

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Disclaimer: please use this feature carefully.

Sometimes we need to render HTML (that comes from a source that we trust!) directly into a component, for instance when we're using a WYSIWYG editor that we control.

In this quick lesson we're going to learn how to use @html in order to render HTML markup from a textarea into a div element.

Instructor: [00:00] We have this simple app with a text area component. Whatever we are going to type in, inside of this text area, we would like to render inside of this diff over here. To do that, we need to bind the value of this text area to this stringToRender variable.

[00:12] In order to do that, bind value = stringToRender. Right now, if I type "Hello Egghead," this text is going to appear over here. I would like to be able to paste in some HTML, and have it rendered inside of this diff. In order to do that, we need to add the @html syntax in front of this string to render variable.

[00:32] If I save, and paste this HTML again, we're going to see it rendered over here. Bear in mind that if you decide to use this feature, Svelte is not going to sanitize any string that you decide to render using @html, so you have to be careful not to expose your users to an attack.