How to render a HTML string in React? - reactjs

I have a string like < b >hi< /b >. I have to render it as "hi". Can someone let me know an equivalent thing like innerHTML in Angular that I can use in React?

you can try dangerouslySetInnerHTML with the enclosing tag:
<div dangerouslySetInnerHTML={{ __html: yourhtml }} />

According to official React docs
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}

To avoid the potential security vulnerabilities (such as XSS attacks) that are present when using dangerouslySetInnerHTML, you can do the following:
First use DOMPurify to clean the HTML.
import DOMPurify from 'dompurify';
let clean = DOMPurify.sanitize(dirtyHtmlString, {USE_PROFILES: {html: true}});
Then it can be rendered using react-render-html as Salman Lone said:
import renderHTML from 'react-render-html';
<div>
{renderHTML(clean)}
</div>

in my case, I used following pacakge.
react-render-html

According to the website "https://reactjs.org/docs/dom-elements.html" you should use dangerouslySetInnerHTML in order to avoid cross-site scripting (XSS) attacks. However, if you are controlling the string that you want to render then that may not be necessary. If you wish to render HTML this way then as the above website explains, you may do so in this way:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
I personally do not like the dangerouslySetInnerHTML method (mostly because it has the word dangerous and that scares me). I cannot say if the next method is better, safer, faster etc but I like it much more. The second method that you can use is to render the HTML with useRef.
An example of this method is:
import React, {useRef, useEffect} from 'react'
export default function Example() {
const aRef = useRef()
const content = '<p style="color:red">hello</p><h1>world</h1>'
useEffect(()=>{
if(aRef==null)return
aRef.current.innerHTML = content
},[aRef, content])
return <div ref={aRef}/>
}
I forgot to do testing for setting class, id, ref, values etc via string.
If someone wants to add to this answer, please add examples for every React operation like I have done with style.

Related

Next js | React - How to insert Google Ads in a page with dynamic content

I'm fetching articles from an API, and then I parse the HTML code:
function Article({ article }) {
return (
<PageContainer>
<div className={styles.container}>
{parser(article.content.html)}
</div>
</PageContainer>
)
;
}
My question is whats the best approach to insert a GoogleAdComponent when I get something like <div class='google_ad'></div> from the API?
I've tried adding a useEffect, check if there's a class with that name, then appendChild, but in React we need to create an element as a React Node and then add it to React.render() right?
I'm getting a feeling that there's an easier implementation, but I can't find any information online about this.
Thanks in advance :)
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
https://reactjs.org/docs/dom-elements.html
But never use it with user input, only with trusted origins

#tippy.js/react allowHTML

In react Tippy I cannot make work some properties of tippy. I want allowHTML in Tippy.
Here is my code:
<Tippy
// content={<div dangerouslySetInnerHTML={{__html: tooltip}} />}
content={tooltip}
delay={100}
hideOnClick={false}
allowHTML={true}
>
...some other code here
</Tippy>
The commented code does what I would like to see. If the content contains html then it renders the content properly. I have found the solution here: https://github.com/atomiks/tippyjs-react/issues/94#issuecomment-498100958
However, I would like to use the own properties of tippy.
allowHTML does not work while delay and hideOnClick work.
It seems like the properties with "R" (see attached picture) do not seem to work and I cannot figure out how to use them in react and could not find in documentation either.
Tippy properties V6.x
Source: https://atomiks.github.io/tippyjs/v6/all-props/
My main issue with dangerouslySetInnerHTML was XSS vulnerability. That's why I wanted to use own property of tippyjs, the innerHTML. Because I though it handles XSS vulnerability but after reading the documentation again, more carefully, I realized it requires sanitizing data as well.
So I just go with dangerouslySetInnerHTML and sanitize my data before using it.
Here is my code:
import Tippy from '#tippy.js/react';
import dompurify from 'dompurify';
import React from 'react';
const PropertyLabel = ({ label, tooltip }) => {
const sanitizedTooltip = dompurify.sanitize(tooltip);
return (
<Tippy
content={<div dangerouslySetInnerHTML={{ __html: sanitizedTooltip }} />}
delay={100}
>
...some other code here
</Tippy>
);
};
Here are the sources that I used to implement dompurify:
https://pragmaticwebsecurity.com/articles/spasecurity/react-xss-part2.html
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml:~:text=class%20attribute%20instead.-,dangerouslySetInnerHTML,-dangerouslySetInnerHTML%20is%20React%E2%80%99s
https://www.npmjs.com/package/dompurify
I know it does not solve the problem of using properties of Tippy marked with an "R" in React, but this single solution works instead of "allowHTML" property.

I want to write other languages code in react js

I am working on building a website.
I made all things, but now I'm stuck in adding code to the website.
I want to put some codes inside the JSX component but it is having some problems with adding { <<these types of symbols.
Is there any way I can write the C++ code or C code inside the react element?
import React from 'react'
const Template = () => {
return (
<div>
<h1></h1>
</div>
)
}
export default Template
The JSX won't appreciate the "{ <<", but if you want a quick in on this, you may try something like this -
const SomeCode = ()=><code>{`#include <stdio.h>;`}</code>
That might not be sufficient - you may need proper highlighting with specific programming language, formatting, etc. for what you might be building. But just for getting literals such as << working with JSX - you may take the above example as base.
In JSX, which is what react usees, brackets will be parsed.
Therefore, strings should be inside {`content`}, or you can define that code as a string, and place it inside jsx as below
const SomeComponent = ()=>{
const codeSnippet = `{ << whatever code blahblah`
return <div>
{codeSnippet}
</div>
}

How to render a template string as HTML?

Let's say I have a simple template string :
const foo = `<div>foo</div>`;
How do I go about rendering this template string as HTML ?
It renders it as plain text if I do the following :
return({ foo });
Output:
<div>foo</div>
Expected output:
foo
I think what you try to do is
const foo = `<div>foo</div>`;
<div dangerouslySetInnerHTML={{ __html: foo }}></div>
Related question.
React documentation.
You note reactjs as a tag here. Instead of specifying the html as a string, make foo a functional react component.
To do that, make sure you have import React as 'react';.
Then, set foo as the functional component, i.e.:
const foo = () => <div>foo</div>;
Then, you can use that wherever you please. React components are just functions (or classes) that return jsx.
Your question is fairly open-ended, so you may be looking for some of the above answers, but this is one approach.
Off the top of my head there's 2 ways to parse a string (doesn't have to be a tl) into HTML: .innerHTML property and the more powerful .insertAdjacentHTML() method.
Demo
var tl = `
<video src='http://media6000.dropshots.com/photos/1381926/20170326/005611.mp4' controls width='320'></video>`;
document.body.innerHTML = tl;
document.body.insertAdjacentHTML('afterbegin', tl);
if you want to show the string of html as html page its better to do this:
<text>{{ info | safe }}</text>

Output object name other than React with jsx syntax

with React v0.12 the #jsx pragma is gone which means it is no longer possible to output jsx with anything other than the React.METHODNAME syntax.
For my use case I am trying to wrap the React object in another object to provide some convenience methods thus, in my component files, I want to be able to write:
var myConvenienceObject = require('React-Wrapper');
var Component = myConvenienceObject.createSpecializedClass({
render: function () {
return <div />
}
})
However the jsx compiler automatially converts <div /> into React.createElement("div", null)
With older versions of React it was possible to handle this using the pragma at the top of the file. However, since that has been removed, I was wondering if there was any way currently to change the name of the object compiled by jsx so <div /> would be transformed into myConvenienceObject.createElement("div", null)
No, it's no longer possible to use a custom prefix for JSX. If you need to do this, you'll need to modify the JSX transform code, or create a fake React.
var React = require('react'), FakeReact = Object.assign({}, React, {
createElement: function(component, props, ...children){
// ...
// eventually call the real one
return React.createElement(component, props, ...children);
}
});
module.exports = FakeReact;
And then to use it you import the fake react and call it React.
var React = require('fake-react');
// ...
render: function(){ return <div />; }
If you would like to make some elements contains in your myConvenienceObject, you could consider the children props as shown in the doc. But this may need some changes in the myConvenienceObject too, to accept the children.
By the way, i'm not sure where is this createSpecializedClass functions comes from and what it does

Resources