简体   繁体   中英

Print text with html tags from database - Javascript

I am using CKEditor in my React App to save user content into the Firebase database. Content is saved as I want it (eg. with html tags "<p>contentheheheh</p>\\n" ) but the problem occurs when I want to fetch the data.

As a result of fetch, let's say into a of I get text with html tags, not 'converted' into bold or italic for example.

When I get into Chrome console and inspect element I see something like this:

<td>&lt;p&gt;I am&amp;nbsp;&lt;strong&gt;testing&amp;nbsp;&lt;/strong&gt;&lt;em&gt;text&lt;/em&gt;&lt;/p&gt;

The thing is I worked with 'raw' db inputs before in Laravel or Symphony, but I don't know how to do it in javascript. I tried to look for it in google and stack but to be honest I failed because I don't even know what exactly is a question, since 'fetch raw data from db in javascript' didn't worked exactly as I imagined.

Thanks for any advice in advance.

PS I know that in Jquery there was something like this:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

But I don't know how to write this in pure javascript (or ES6).

You can do it with RegExp replacement:

var text = '&lt;p&gt;I am&amp;nbsp;&lt;strong&gt;testing&amp;nbsp;&lt;/strong&gt;&lt;em&gt;text&lt;/em&gt;&lt;/p&gt;';

var decoded = text.replace(/"&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, "\""); 

Probably (without code sample i can't really know) the cause of what is happening doesn't come from fetch but from rendering.

By default react escapes html tags when rendering a component.

To avoid escaping and set html of a component use dangerouslysetinnerhtml ( https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml ).

Okey so I spent at this problem whole night BEFORE I asked the question, and just after I did that, I managed to resolve the problem.

  1. I installed 'he' library from npm package (npm install he)
  2. I installed 'html-react-parser' (npm install html-react-parser).

First one is used to decode html from database. Second one is to write this html into jsx elements.

Example:

let text = he.decode(props.tdData[item]);
return (<td>{Parser(text)}</td>);

This two libraries do it for me and it works just as I wanted.

Thanks for any input you made, case is closed :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM