React: how do I render source code in a variable? - reactjs

I store some html source code in database, it's a block of code like this:
<div class="content"><h1>Page 1</h1></div>
Now in react I get them in a variable ({this.state.content}), but when I try to render them the source code got displayed as a string. Here's how I use it:
<div>
{this.state.content}
</div>
On page it just shows the source code directly. How do I get them render as html source code instead of a string?

Actually, you are trying to set raw HTML. Try this.
<div dangerouslySetInnerHTML={{__html: this.state.content}}></div>
Duplicate of this question

Related

React - Insert an image between the 2nd and 3rd <p> tag

I have a React component
<Text>
<div dangerouslySetInnerHTML={{ __html: apiContent}} />
</Text>
that displays HTML coming from an API that may look like the following:
<div>
<p>text</p>
<p>more text</p>
<p>more text</p>
<p>more text</p>
<p>still more text</p>
</div>
How do I insert an image, which is another React component, between the 2nd and 3rd p tag?
I know how to do it in vanilla JS, but have trouble doing it the React way.
I'd be curious to see the other answers, but I feel like inserting a React component inside some raw HTML is pretty much impossible. The options I can think of are:
use some library to turn the raw HTML into a tree of React components, and hopefully this library will also include a way to inject custom components in specific places (I don't know any such library, but there probably is one)
edit the raw HTML to insert an empty container with a unique id at the place you need it (for instance by parsing the HTML into a DocumentFragment, using vanilla JS to insert a div, turning it back into a string, and setting it as innerHTML as you already do), and then use a React portal to inject a React component into that container. Pretty messy...
If it is a react component then it is not html so not logical to put it inside dangerouslySetInnerHTML tag.
you need to rewrite this react component to an HTML string and work with the html that is coming from API as a string.
that means you can split the incoming string of html on the second closing p tag
and add the new html string in the middle.

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 do plug in data inside a url string in React?

I'm trying to get some data from my state passed down into this img
src url, and I can't seem to figure how to write it. I've tried using back
ticks and the dollar sign. I assume because I'm down in the render part
of the Component that won't work. Help me Obi-Wan, you're my only
hope.
<img src={'https://openweathermap.org/img/w/{data.weather.icon}.png'} alt='weather condition' />
Just like with vanilla JS, you have to use a Template Literal and use string interpolation to place your JS within the string (with a ${...}) like so:
<img src={`https://openweathermap.org/img/w/${data.weather.icon}.png`} alt='weather condition' />
you can use Template Literal
<img src={`https://openweathermap.org/img/w/${data.weather.icon}.png`} alt='weather condition' />

convert angular view to static html

I hvae an angular view of a pdf preview that utilizes a controller to fill the view in. I am using pdflayer then to convert the html page into a pdf. The problem however is that no matter how I try and do this the scope variable values never make it into the pdf. I am basically trying to figure out a way to capture the angular view as an html string (data already injected) so that I can pass it to pdflayer. I have tried creating a directive and used replace within the directive then collecting the DOM as a string using .HTML().
For example:
I could like this
<div id="name">{{test.name}}</div>
to become this
<div id="name">Bob Smith</div>
It inevitably however turns into this when i use $('#name').html() and then console log it
<div id="name"></div>
or
<div id="name">{{test.name}}</div>
Any help would be appreciated even if the solution is to use a different method to create the pdf. Ultimately, I need to get a angular view into a formated pdf.
Please check if below library would work for you : https://www.npmjs.com/package/angular-save-html-to-pdf

Having trouble rendering youtube search data using handlebars.js

Im using the youtube data API and would like to template out my video search results but at the moment I'm a little confused about the paths to render out each piece of data, my data structure is, btw I'm using Backbone and parsing the response to return response.items.
Data
And my template looks like this:
<div class="video" title="{{snippet.title}}" id="{{id.videoId}}">
<img class="video-image" src="{{snippet.thumbnails.default.url}}">
<p class="video-title">{{snippet.title}}</p>
<p class="video-author">{{snippet.channelId}}</p>
<p class="video-description">{{snippet.description}}</p>
</div>
Also is this the correct type of search result data? How can I get likes/dislikes etc?
If I understand your problem correctly, you're having trouble getting the template to correctly render your data? If so:
The data you get back in response.items is an array, so you'll have to loop over them in the template.
Modify your template like this:
{{each results}}
<div class="video" title="{{snippet.title}}" id="{{id.videoId}}">
<img class="video-image" src="{{snippet.thumbnails.default.url}}">
<p class="video-title">{{snippet.title}}</p>
<p class="video-author">{{snippet.channelId}}</p>
<p class="video-description">{{snippet.description}}</p>
</div>
{{/each}}
Assuming you've compiled the Handlebars template into a variable called template, you can do this:
var context = {
results: response.items
};
var html = template(context);
Notice that the context object has a results property, which is the array that gets looped over with the {{each results}}.
Since you're using Backbone, you'll probably want to update the view with
this.$el.html(html);. Don't forget to return this; from the render method too!
As far as the type of search results data, I don't know if that's the right or wrong results...that's up to you. What kind of results do you want? Is the data you're getting what you're looking for?
If you want Likes/Dislikes, you have to look that up on a per-video basis. Register your application for the YouTube v3 API, and perform a GET request to the Videos resource (API Documentation). This will return a list of matching Videos (Video resource documentation), which have a likecount and dislikecount.

Resources