0

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
Afia
  • 683
  • 5
  • 17
Rom
  • 563
  • 5
  • 21

3 Answers3

2

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.

dns_nx
  • 3,651
  • 4
  • 37
  • 66
0

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;
Priyank Thakkar
  • 4,752
  • 19
  • 57
  • 93
0

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.

Community
  • 1
  • 1