How to set innerHTML react js format - javascript

So I given this code:
render() {
console.log(this.props, 'ey');
const var1 = "<div className={{blahblah}} style={{width: '10px'}}>{textvar}</div>"
return (
<div dangerouslySetInnerHTML={{ __html: `${var1}` }}>
</div>
);
}
Of course that's just an example, but the var1 should be a big chunk of html file in jsx format, however doing that one renders them as they are and doesn't convert them to regular html.
I also tried setting innerHTML via refs on componentDidMount but same problem happens.
this is what it should look like when it renders:
<div class="blahblah style="width: 10px"}}>the variable text</div>
Any help would greatly appreciated. thanks!

You need to do this to use ES6 interpolated string literals (inaccurately called template literals by the spec):
<div dangerouslySetInnerHTML={{ __html: ${var1} }}>
But this would be simpler:
<div dangerouslySetInnerHTML={{ __html: var1 }}>
However, in your string for the inner html, you may want to use an interpolated string literal if what you want is to use the values of the blahblah and textvar variables.
Note you need to use class instead of className since React will just set the inner html rather than treat it as JSX and className is only for JSX.
const var1 = <div class=${blahblah}>${textvar}</div>;
If you are using a class, no need to also use the style keyword. Just set the width in your CSS.
You can see a working example of the above on CodePen.

Related

HTML text in span - Tags not getting implemented

I have span -
<span> {textToRender} </span>
I am rendering html text (as string) with span.
some text <br/> some text <br/> some text <ol>text
This is getting rendered as text only in javascript. Html tags are not getting applied over it.
<span> {textToRender} </span>
same as the guys suggest you can use the dangerouslySetInnerHTML,
Although the name suggests danger in dangerouslySetInnerHTML and its use, taking the necessary measure by using a well-developed sanitizer ensures the code to be clean and does not run unexpected scripts when rendered within the React node.
you can use DOMPurify for exemple
import DOMPurify from 'dompurify'
const App = () => {
const data = `lorem <b onmouseover="alert('mouseover');">ipsum</b>`
const sanitizedData = () => ({
__html: DOMPurify.sanitize(data)
})
return (
<div
dangerouslySetInnerHTML={sanitizedData()}
/>
);
}
export default App;
Please try it following way:
<span dangerouslySetInnerHTML={{__html:textToRender}}></span>
I hope it helps you.
This is expected, as React.js automatically escapes the extrapolations to prevent injection attacks and other vulnerabilities. In case you want HTML to get parsed, and proper tags be applied, you can use JSX instead of String or set HTML explicitly as follows:
<span dangerouslySetInnerHTML={{ __html: textToRender }} />
Or
convert your textToRender to JSX.
textToRender = <>some text <br/> some text <br/> some text</>
<div dangerouslySetInnerHTML={{_html:textToRender}}/>

How to render string including JSX component with PascalCase in React?

I have a React app, receiving the blog post data from external cms. The data is raw HTML as a string, like this:
<h1>hello</h1>
<img src="example.com/felan.jpg">
<p>some text</p>
<img src"example.com/another.jpg">
...
Now, I want to replace img HTML tag with a jsx component called Img (with capital I).
I do it with:
let postContentOptimized = post.replace("img", "Img");
<article dangerouslySetInnerHTML={{ __html: postContentOptimized }} />
But it automatically converts Img to img (changes PascalCase).
I also tried with other component names, and it throws this error:
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
I found a package called react-jsx-parser.
Its documentation isn't straightforward, thus I skipped it the first time I found it.
Here's how to do it if you're confused like me:
<JsxParser components={{ components used in your string }} jsx={the string you want to parse} />
example:
<JsxParser components={{ Img }} jsx="<Img src="hello.png /><p>hello</p>" />

Global JS variable to pass HTML chunk to React component

I have a piece of HTML I need to send to a React component on page load without rendering it. I'd rather not us AJAX due to cache, but I may revert to that if I can't figure this out.
On the jsp side, I have this:
<script>window.banner_data_for_desktop = "...droplet..."</script>
This contains the HTML chunk I need to pass
<div id="desktop-top-banner">
<div>
...
</div>
</div>
On the jsx side, I've tried rendering directly like this:
<div id="top_bar">{window.banner_data_for_desktop}</div>
This renders the content, but displays the div tags as a string and not output as HTML.
So then I tried using dangerouslySetInnerHTML like this:
<div id="top_bar">dangerouslySetInnerHTML={{ __html: window.banner_data_for_desktop }}</div>
This results in an error:
Invariant Violation: Objects are not valid as a React child (found: object with keys {__html}). If you meant to render a collection of children, use an array instead.
I've tried using Stringify, toString, creating a function to return the html like this:
function createMarkup() {
return {__html: window.banner_data_for_desktop};
}
All without any luck. If any one has a suggestion to render HTML from the global JS object, I would greatly appreciate it!
dangerouslySetInnerHtml should be an attribute of the tag:
<div dangerouslySetInnerHTML={{__html: "HTML CHUNK"}}></div>

Manipulate dom element outside React component

I have a React component that renders HTML only on a small part of a HTML document.
From within the React component I need to replace an element, that exist outside the component, with a block of HTML.
No matter how much I'm googling this, I cannot find a straight way to accomplish this, I assume that it's because React's guidelines that naturally prescribe to use ref instead.
How would I use document.getElementById() or anything similar to insert the following sample HTML block at the place of a certain div:
<div>
<div class='yellow'>YELLOW</div>
<div class='green'>GREEN</div>
<div class='blue'>BLUE</div>
</div>
Assign an id to the top level element of the html react renders. It will still include the id attribute and thus can still be referenced with document.getElementById
<div id="toReplace">
<div className="yellow">YELLOW</div>
<div className="blue">blue</div>
<div className="red">red</div>
</div>
componentDidMount() { //or wherever
document.getElementById('toReplace').append('more html');
}
const str = "<div><div class='yellow'>YELLOW</div><div class='yellow'>GREEN</div><div class='yellow'>BLUE</div></div>"
document.getElementById('toReplace').innerHTML = "";
document.getElementById('toReplace').insertAdjacentHTML( 'beforeend', str );

Dynamic variable in multiple language with dangerouslySetInnerHTML

I use laravel with react, so doing {Lang.get('profile.name',{name: someVar})}will return me some value from my English language file. But I have to mix some html tag as I want the name to be bold, thought of using dangerouslySetInnerHTML but failed with the code below
<div dangerouslySetInnerHTML={{
return {__html: Lang.get('profile.name', {name: '<strong>someVar</strong>'}})}
}} />

Categories