If I have a javascript variable, for example in react:
{variable}
And if I print it I get:
one<br><br>None
How can I change the <br><br>
that comes from the database for the html breakline and get as result:
one
None
If I have a javascript variable, for example in react:
{variable}
And if I print it I get:
one<br><br>None
How can I change the <br><br>
that comes from the database for the html breakline and get as result:
one
None
You do this with the function dangerouslySetInnerHTML
.
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
<div dangerouslySetInnerHTML={{__html: variable}} />;
Then HTML codes will be rendered as such.
I think when you receive string
from database, it is string and not html element and react cannot display it as html element. You can use this react-html-parser to convert such html templates received from database to display as html element.
import React from 'react';
import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser';
const StringToHtml = () => {
// retrieves variable here
return (
return <div>{ ReactHtmlParser(variable) }</div>;
);
}
export default StringToHtml;
By default, React escapes the HTML to prevent XSS (Cross-site scripting). If you really want to render HTML, you can use the dangerouslySetInnerHTML property:
<div dangerouslySetInnerHTML={{__html: variable}} />
Or you can use any node package which parse html strings.