The html
function uses Preact under the hood, which does not render inserted html tags. This behavior is intended to prevent XSS injections.
If you’re sure that the input is safe, you can use the dangerouslySetInnerHTML
prop to bypass this behavior. The resulting template would look like this:
item(hit, { html, components: { Highlight } })
{
return html`
<h2> <${Highlight} attribute="name" hit=${hit} /> </h2>
<p dangerouslySetInnerHTML=${{ __html: hit.description }} /> `;
}
You can find a demo of this functionality here.
***
If you are using an older version of InstantSearch without the html
function, you should use the workaround below.
When one of your attributes has \n
in its JSON string, InstantSearch will not display the value as a line break. This is because the Hits widget renders the attribute value as HTML. You can use the transformItems function to replace the \n
string with <br>
and achieve the desired result.
Here is a working CodeSandBox showing this workaround in action and below is the example data used in the first hit returned.
"name": "Amazon - Fire TV Stick with Alexa Voice Remote - Black",
"description": "Enjoy smart access to videos,\n games and apps \n with this Amazon Fire TV stick. \n Its Alexa voice remote lets you deliver hands-free commands when you want to watch television or engage with other applications. With a quad-core processor, 1GB internal memory and 8GB of storage, this portable Amazon Fire TV stick works fast for buffer-free streaming.",
Here is the relevant code for the transformItems function that replaces the \n
string with <br>
.
transformItems(items) {
return items.map((item) => ({
...item,
description: item.description.replace(/(?:\r\n|\r|\n)/g, '<br>'),
}));
},