Using HTML placeholders in React - reactjs

I grab content from a CMS via Gatsby. Inside the markup there are placeholders which should be replaced with React elements.
So I get sth like this:
let content = '<span>Hello World [placeholder]!</span>';
and in React I want to change it to sth like this (where the markup for the tooltip comes from a React element):
let content = '<span>Hello World <div class="tooltip">Important warning</div>!</span>';
The final html with the replaced elements should be dumped into the DOM using dangerouslySetInnerHTML.
I tried using react-string-replace:
reactStringReplace(content, '[placeholder]', () => (<Tooltip />));
but it gives me an array containing a mix of strings and React elements that can't be concacenated without breaking the HTML structure.
What would be a good approach to tackle this issue? Or am I wrong using placeholders in the CMS altogether?

i found a really good npm package that provides this functionality and much more: https://interweave.dev/

Related

Dangerously Set innerHTML React

I have React frontend and strapi backend.
When inserting data into my strapi backend, the resulting output in my frontend contains html elements.
How can I show the output without the HTML elements? I have the following Gatsby code block,
import ReactMarkdown from "react-markdown"
<ReactMarkdown children={info_} />
The data within {info_} is outputted with the HTML elements, how can I use Dangerously Set innerHTML in my code or is there some other way to achieve this?
If you display an html node within the dangerouslySetInnerHTML property, you put your application at risk for XSS attacks. Long story short, the html could contain malicious code that would harm the user. If you do it, you need to sanitize the content before displaying it. The best option would be to use a battle-tested library such as sanitize-html-react.
You can use DOMParser to create a document from your HTML input and then extract the text like this:
new DOMParser().parseFromString(info_, 'text/html').body.textContent;
Here's an example using a functional form:
I tried putting this into a snippet demo, but the Stack Overflow snippet environment doesn't like something about the syntax. 🤷 ☹️ You can copy and paste it in your JS console to try it.
Note that the embedded script never runs, but its source text is included in the output. If you want just part of the created document's text, you can use a method like Document.querySelector on the created document rather than its body.
function getTextFromHtml (html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent ?? '';
}
// Use:
// assuming `info_` is a string of valid HTML like this:
const info_ = `
<div>
<p>Some text</p>
<p>Some more text</p>
<script>console.log('This script executed!')</script>
</div>
`;
const textContent = getTextFromHtml(info_);
console.log(textContent);
Afterward, you'll have plain text, so you won't need dangerouslySetInnerHTML.

How to render math type tags in reactjs from string?

SO, I am trying to render html (mixed. i.e normal plus math type tags) using react-html-parser.
It is able to render the normal html but could'nt render the math type tags.
Is there a plugin to render both of them.
Following is my string containing both the content.
"<p>Math test<br />↵<math xmlns="http://www.w3.org/1998/Math/MathML"><msqrt><mn>25</mn></msqrt></math> <math xmlns="http://www.w3.org/1998/Math/MathML"><msup><mn>2</mn><mn>3</mn></msup></math> <math xmlns="http://www.w3.org/1998/Math/MathML"><mo>∪</mo><mn>2</mn></math> </p>↵"
Thanks.

How to use angular.element() in Vue

I used like this in angularjs before. And now I m moving to Vuejs.
How can it be replaced in Vuejs?
angular.element(document.querySelector('.popup-inner#company-etc')).css('display', 'none');
You can use $refs
<div ref="companyEtc" class="popup-inner" ...
...
this.$refs.companyEtc.style.display = "none"
I would advise to use conditional rendering: https://v2.vuejs.org/v2/guide/conditional.html
You also can find more information about getting element in a component in answers to the question: Vue.js getting an element within a component

Preserving <pre> tag whitespace when displaying content from Firebase with dangerouslySetInnerHtml

Here's the background:
I want to be able to save rich text blog posts to Firebase to then display them, including code snippets, on a Posts page.
Right now, I'm simply saving a single string of html to Firebase, retrieving that per post, and setting it with dangerouslySetInnerHtml. I'm the only one adding posts.
However, this means that I lose tabbing information when displaying code snippets in blocks. I don't think I can use solution since I'm using dangerouslySetInnerHtml: Formatting code with <pre> tag in React and JSX
Any tips on how to store, retrieve, and display rich text using React and Firebase? Thank you for your help.
I was able to use the following to convert rich text to html, and then minify it:
https://4html.net/Online-HTML-Editor-Text-to-HTML-Converter-870.html
http://minifycode.com/html-minifier/

React : best way to inject Component in dynamically loaded HTML?

I'm new on React (I more at ease w/ jQuery or AngularJS). I have a special case and I don't find a good way to resolve it...
My app contains an area which is like a "document viewer". It loads an HTML content from the backend (via API, using Fetch) and inject it in the "viewer" component. The HTML content loaded looks like an "university report" (it's just a formatted text, only <span> and <p> with class="..." attributes, nothing more).
Ex : <p>Lorem ispum <span>some text</span> loreb bis <span>ipsum</span></p> ...
I load the content, and inject it this way in the render() of my component <Viewer> :
<div dangerouslySetInnerHTML={ getFreshlyLoadedHTML() } />
Easy, it works just fine !
But... Now, I want to inject some "interactive" components in the loaded HTML. For example, some button to give a feedback etc. The API must decide where to place the component between the words/nodes of the formatted text (HTML).
Ex :
<p> Lorem ispum <span>some text</span>
loreb bis <span>ipsum</span>
<MyFeedbackButton paragraph="1.3"/>
</p><p>Other Lorem Ipsum<p><span>...</span>
There, I'm stucked because I cannot use dangerouslySetInnerHTML if there are components inside the loaded HTML...
First attempt : I've tried modifying the API, and instead of sending the HTML in a string to the app, I send a custom JSON structure that represents almost the final JSX structure that I want. Then, in my react page, the render function only have to parse the JSON and build the JSX (here, a JsFiddle example if it's not clear : https://jsfiddle.net/damienfa/69z2wepo/34536/ )
It works, but I can't believe it's the good way...
I see a major problem : all the HTML node (span, p...) that I build from the render function are referenced by reactJs, is it really necessary ? Mostly, there are "dead" nodes (I mean, dom node that won't never changed, this is static formatted text).
Just take a look a all those "data-reactid" on nodes that never will be interactive...
What would be your advice on that case ?
What about my attempt with a JSON-structure sent by the API ?
Is there a way to say to react "do not reference that element" ?
Do you clearly see a better solution to my problem ?
Your current workflow is not very secure and subject to many potential errors and open doors, especially concerning code injection ...
The overload due to react tracking the nodes is not an issue, React could track 10 000 nodes and not have a problem (well actually on many of my apps React has more than 100 000 nodes to care about and it still rurns perfectly).
I see different solutions here:
If there are only 3 or 4 possibilities of dynamic components and order, you might have components like "templates" to which you would simple send text arguments. This is the safest and easiest option.
If it doesn't suit your use-case but the JSON file can contain only a limited set of components, the components should be located in your main app, and then rendered with custom props from the JSON. Actually given the structure of data you could consider using xml instead of json and build a xml tree that you would parse and render. Only components from your white list would be rendered and it would limit drastically the potentials security issues. If needs quite some work on the XML parser though.
If the JSON file can contain many many different and unpredictable components or if the behaviour of those components is largely dynamic and independant of your app, you might as well consider using an iframe, with its own JS and HTML, so that this part of the code is isolated from the rest.
Try using an inline anonymous function within the inner content from within React using JSX. It works! Just be careful about how you wire up the data so there isn't a route where a user can inject HTML from an input or text field.
<div className="html-navigation-button">{(() =>
{
const CreateMarkup = ( sNavItemName :string ) => {
return {__html: sNavItemName };
}
var sTextToAddHtmlTo = props.nextNavItem.name.toString();
sTextToAddHtmlTo = sTextToAddHtmlTo.replace( "/", "/<wbr>" );
return (
<div dangerouslySetInnerHTML={CreateMarkup( sTextToAddHtmlTo )} >
</div>
);
})()}
</div>
I didn't override the React internals of 'render()', but only used a React Component with props wiring to pass down data to it for rendering.
I added the hook for 'dangerouslySetInnerHTML' deep within the return content of the React Component so there would be no easy way to intercept and manipulate it.
As such, there is no 100% guarantee on safety, but that's where adding good security to web services, databases, and use of CORS and CORB would be helpful to lock down security risks.

Resources