Dynamic variable in multiple language with dangerouslySetInnerHTML - javascript

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>'}})}
}} />

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>" />

How to set innerHTML react js format

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.

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>

How to render HTML Template and bind data from JSON response in ReactJS?

I have to render an HTML template using reactjs. HTML template is dynamic and get through an API call. There is provision in template to bind the data in html.
Sample HTML template is as follows,
<a target="_blank" href="{ad.url}">
<div class="ads temp-1">
<h2>{ad.name}</h2>
<div class="adv-content">
<div class="advs-image">
<img src="{ad.image}" />
</div>
<div class="adv-desc">{ad.description}</div>
</div>
</div>
</a>
Here ad is an Object which contains the properties url, image, name, description etc
Sample ad Object is as follows,
var ad = {
"image": "testimage.jpg",
"url": "http: //google.com",
"name": "testadvertisement",
"description": "testdescription"
}
I have achieved this in AngularJs using, $compile service.
Now I want to move this to reactjs.
I have tried to render using reactjs render function, But it didn't help. It renders html as string.
Is there any compile like function in reactjs ? Or could you please suggest any other way to do this right way ?
Any help appreciated.
As I correctly undestand you should use dangerouslySetInnerHTML prop.
For example:
// SomeComponent.js
// other methods...
render() {
// `htmlFromResponse` is your plain html string from response.
return (
<div dangerouslySetInnerHTML={{ __html: htmlFromResponse }} />
);
}
Using this prop, you can render plain html string into div element.
If you are getting html template from server, and want to pass variable to it before rendering, you can do it with Mustache package:
import Mustache from 'mustache';
// template should contain variables in {{ ... }}
const html = Mustache.render(htmlFromServer, {
variable: 'value'
});
Next, you can render output html using dangerouslySetInnerHTML prop.
create a react component which renders the HTML data, then pass your Json data as Prop to the component. this will give React element access to data and Rendered HTML will be automatically updated when Json data changes.
Check out some react tutorial video over youtube, that will give you an overview of how ReactJs works
here is how to Pass Props
https://jsfiddle.net/abhirathore2006/6a403kap/
var Hello = React.createClass({
render: function() {
console.log(this.props)
return <div>Hello {this.props.name}
<h5>{this.props.d1.name}</h5>
id:{this.props.d1.id}
</div>;
}
});
ReactDOM.render(
<Hello name="World" d1={{"name":"test","id":"5"}} />,
document.getElementById('container')
);

Categories