React app rendering html entities such as ampersand as escaped - wordpress

I have a React app embedded in Wordpress page. It pulls content from a JSON api and displays it in various areas.
My problem is that all of the text content that comes from the api displays as escaped charachters i.e & displays where an ampersand should be.
My wordpress page has <meta charSet="utf-8" /> which I would normally expect to convert this, but is having no effecton the React content. Is it because the rendering is done within React? In which case do I need to set React somehow to be using UTF-8?

HTML (including entities) will be rendered as a string when being rendered as an expression:
{htmlString}
In order to parse HTML, there is dangerouslySetInnerHTML prop:
<span dangerouslySetInnerHTML={{__html: htmlString }} />
As the name says, it's unsafe and should be generally avoided. If a string comes from untrusted source or a source that could be exploited, malicious code can be rendered to a client.
The preferable way is to decode entities specifically, e.g. with html-entities:
import { Html5Entities } from 'html-entities';
const htmlEntities = new Html5Entities();
...
{htmlEntities.decode(htmlString)}
The problem could be avoided by not storing HTML entities in the first place if possible.

Related

How to render JSON content from wordpress API to react component?

I am using WordPress as backend API to fetch data, I have an object is v.post.post_content, the console-log is like this: the console logs the v.post.post_content
however, when I tried to use
dangerouslySetInnerHTML={{
__html: v.post.post_content,
}}
the front end does not look good, as it does not have the CSS format.
I tried to use the react-json-pretty package, however, that is for pure JSON, and it is hard to format a json string contains with texts and HTML tags. Is there a better way to do it?

HTML Template vs defining HTML inside web component

I can't seem to grasp or find out why you should use HTML templates with web components when you can simply define the HTML inside the web component (shadowRoot.innerHTML).
What is the benefit of creating a template and cloning it inside the web component? I can see there being a reason if two web components share the same HTML but beside that I have no idea.
Is there something fundamentally important that I'm missing?
Yes, too many blogs do document.createElement("template") where an .innerHTML will do the same ... and with less code ... and faster.
Note, Templates are not tied to the Custom Elements API or shadowDOM.
Each of the 3 Web Components technologies can be used without the other.
Templates
Templates are great when you want to store re-usable content in the HTML Document, because it does not get parsed.
In the old days we would use a <div hidden> and pray its contents did not affect the rest of the page.
Just like the old days you can read the Template.innerHTML and do whatever you want with the String value.
More modern approach is to clone the Template, just be aware that .content property is required, and you get a Document-Fragment value in return.
<template id="MY-TEMPLATE">
<article>
...
</article>
</template>
document.getElementById("MY-TEMPLATE").content.cloneNode(true)
Templates & shadowDOM
When you have Custom Elements with shadowDOM, Templates are great to define that shadowDOM content.
Why so many developers want to do HTML-in-JS and CSS-in-JS I don't understand.
If you have an HTML document, store the content there, way easier to edit.
<template id="MY-ELEMENT">
<style>
/* style shadowDOM here */
</style>
<slot></slot>
</template>
All your MY-ELEMENT then needs to do is:
super() // or this when done in the connectedCallback
.attachShadow({mode: 'open'})
.append(document.getElementById(this.nodeName).content.cloneNode(true))
Performance
an innerHTML String with HTML content will get parsed for every usage.
A template is parsed once, so does save on CPU cycles, when you use the same template many many multiple times
Usage
My personal preference is to keep as much HTML (and CSS) inside <TEMPLATEs> in HTML as possible. Only when I want my components not to be configurable I use static HTML in JS, with .innerHTML, not .createElement("template") for code brevity over (minor) performance gain
Only in SDWCs (Self Destructing Web Components) that need to load/execute ASAP I contain everything inside the Component:
customElements.define('my-head',class extends HTMLElement{
connectedCallback(){
// generate <HEAD> content, <SCRIPTS> and <STYLE> CSS-in-JS here
this.remove();
}
});
What is the benefit of creating a template and cloning it inside the web component?
Speed. Parsing a string and generate internal html objects takes some extra time compared to just cloning nodes. If the web component is used in many places and each will parse string and convert it to html objects. Compare that with just parsing once.
tutorial about web components

WordPress template using React. Incorrect chars

I am creating a WordPress template, using React. I have a WP Post that looks perfect in DB. To retrieve data from the server I use Axios, using the new API feature included in WordPress.
This is how the title looks in the DB:
Hello world! I'm leaving
This is the code I use to retrieve the title from DB:
axios.get('/paintings-project/wp-json/wp/v2/posts').then(
function(response){
self.setState({posts: response.data})
}
);
This is how the post title looks when rendered:
Hello world! I’m leaving
The char ' is escaped, and the backslash used for escaping is encoded.
On the other hand, when rendering HTML content from the post, the HTML appears as a string, instead of rendered as HTML. Like this:
<h1>Welcome’ to WordPress’.</h1> <p><strong>This is your first
post. Edit or delete it, then start writing!</strong></p> <p> </p>
I expected the WordPress APIs would work straight without need of special encoding / decoding in BE or FE. Am I doing something wrong?
Thanks
React doesn't allow you to render strings as HTML in that way. You're going to have to use the dangerouslySetInnerHTML attribute (docs) to render your HTML string in your component.
Something like:
renderStr() {
return {__html: this.state.dataToRender};
},
render() {
return <div dangerouslySetInnerHTML={renderStr()} />;
}
Bear in mind, as the attribute name suggests, you'll want to make sure that the HTML you're rendering is safe. If it's coming from user input, make sure to sanitize the input before storing/rendering it or you can expose yourself and others to security risks. You can use an NPM dependency like sanitizer or sanitize-html, or you can write a function to do it yourself.

Seeing html code in tooltips in asp.net

I am parsing web service xml and populating a treeview in asp.net. I'm trying to display one of the xml node attributes as a tooltip, but that attribute happens to sometimes have html tags in it. I know there seem to be some custom tooltip stuff out there, but I don't have the time or the experience to play with those yet. Is there no way to easily remove such code or translate it into the textual equivalent? I know I can replace br tags with environment.newline, but I don't want to have to do this for every conceivable html tag that might be embeded in the content!
The HTML Agilty Pack is an HTML parser that can read HTML fragments - you can do that and then read the InnerText property of the top node. The effect will be a textual version of the HTML.

Dynamically loading CSS elements in asp.net

I searched google and SO, but did not find a solution.
I have an asp.net web app that allows users to customize some GUI aspects (such as font color, add a custom logo etc). This information is stored in the user profile database.
I have a css file that populates font colors etc. The main page, loads the users profile from the database, and customizes the page accordingly.
Aside from having each label with its own "font-color=", how can I display the CSS elements, based on the user profile information returned from the database? Thx
You can include an extra CSS file that points to an ASPX page:
<link rel="stylesheet" type="text/css" href="/CustomStyles.aspx" />
Then in CustomStyles.aspx change the default content-type:
Response.Clear()
Response.ContentType = "text/css"
Then just start outputting your styles:
Response.Write("#awesome-button{color:" & ColorFromDatabase & ";}"
Make sure that this file is included after the other styles so that it takes precedence. You might want to also throw an !IMPORTANT in there, too.
Response.Write("#awesome-button{color:" & ColorFromDatabase & " !IMPORTANT;}"
It depends on how you have the information stored, but you can add styling to elements through code like this:
Button1.Style["font-weight"] = "bold";
Or you can just apply a CSS class to the control:
Button1.CssClass = "buttonStyle";
You could have a page that just returns a CSS file based on the preferences stored in the database. So you would have:
<link rel="stylesheet" href="somepage.aspx?userid=<%=userID%>">
You could probably even do that easily enough with a classic ASP page, a web service, etc.
The point is that that page would generate the same basic stylesheet, filling in the right colors etc. that the user has chosen. This way you don't have to perform a bunch of style changes in server-side or client-side code after the page has loaded, or mix your user preference code in with your HTML, or change much about the base pages if you want to change the way the stylesheet works. It also makes it easy to test your stylesheet outside of testing the site itself.

Resources