Parse and Render external HTML in React component - javascript

I'm writing a React-based application where one of the components receives its HTML content as a string field in props. This content is returned by an API call.
I need to:
Render this content as a standard HTML (i.e. with the styles applied)
Parse the content to see if the sections within the content have "accept-comments" tag and show a "Comment" button beside the section
For example, if I receive the HTML below, I should show the "Comment" button beside section with id "s101".
<html>
<head/>
<body>
<div id="content">
<section id="s101" accept-comments="true">Some text that needs comments</section>
<section id="s102">Some text that doesn't need comments</section>
</div>
</body>
</html>
Questions:
What would be the most efficient way to parse and render the HTML as the content can get a bit large, close to 1MB at times?
How can I ensure that React does not re-render this component as it will not be updated? I'd assume always return "false" from shouldComponentUpdate().
Things I've tried:
Render the HTML with "dangerouslySetInnerHTML" or "react-html-parser". With this option, cannot parse the "accept-comments" sections.
Use DOMParser().parseFromString to parse the content. How do I render its output in a React component as HTML? Will this be efficient with 1MB+ content?

This answer comes from Chris G's code in the comments. I used the code with different sizes of documents and it works well. Thanks Chris G!
Posting the code here in case the link link in the comments breaks.
The solution uses DOMParser to parse the HTML content provided by the API call and scans it to find the content that should include the "Comment" button. Here are the relevant parts.
import React from "react";
import { render } from "react-dom";
const HTML =
"<div><section but='yes'>Section 1</section><section>Section 2</section></div>";
class DOMTest extends React.Component {
constructor(props) {
super(props);
const doc = new DOMParser().parseFromString(HTML, "application/xml");
const htmlSections = doc.childNodes[0].childNodes;
this.sections = Object.keys(htmlSections).map((key, i) => {
let el = htmlSections[key];
let contents = [<p>{el.innerHTML}</p>];
if (el.hasAttribute("but")) contents.push(<button>Comment</button>);
return <div key={i}>{contents}</div>;
});
}
render() {
return <div>{this.sections}</div>;
}
}
const App = () => (
<div>
<DOMTest />
</div>
);
render(<App />, document.getElementById("root"));

Related

Render one component several times in different html pages with different text

I'm new to react and I'm trying to render one component in different html files (because I'm working in an existing project), each of them with different text.
I'm thinking of something like this:
class ctaSection extends React.Component{
render(){
return(
<div className="cta-section">
<div className="md:w-9c">
<h5 className="uppercase">{this.props.h5}</h5>
<h3>{this.props.h3}</h3>
</div>
<div className="cta-button">
<a href="#">
<button className="w-full">{this.props.button}</button>
</a>
</div>
</div>
);
}
}
export default ctaSection;
Then, in my index.js, I'm rendering like this, passing the props:
let ctaPage1 = document.getElementById('cta-section-page-1');
let ctaPage2 = document.getElementById('cta-section-page-2');
ReactDOM.render(<CtaSection h3='my text for page 1' h5='my h5 for page 1' button='hello'/>, ctaPage1);
ReactDOM.render(<CtaSection h3='text for page 2' h5='something' button='click me'/>, ctaPage2);
I'm not sure if this is the best and simpler way to do this, because I'm calling ReactDOM.render twice for same component, and I got this error:
Uncaught Invariant Violation: Target container is not a DOM element.
This works fine if I render the component once, but not for multiple instances.
What is the best way to do it?
I've thought about this more, and I'm not experienced with adding React to existing websites, but here's what I'd suggest:
I would have 1 JS file per HTML page that imports CtaSection, each of those files would look like such:
// page1.js
import CtaSection from '../CtaSection'; // or wherever it is
let ctaPage = document.getElementById('cta-section-page');
ReactDOM.render(<CtaSection h3='my text for page 1' h5='my h5 for page 1' button='hello'/>, ctaPage);
You would just need to make sure each html page uses the corresponding JS file.
// page1.html
<body>
<div id="cta-section-page"></div>
<script src="page1.js"></script>
</body>
Repeat for each page.

React: How to use same component twice in same page but loading one script tag for both just one time

I created a react component that I want to use twice(or more) inside my page, and I need to load a script tag for it inside the head of my page but just once! I mean even if I use the component twice or more in the page it should add the script tag just once in the head.
The Problem is that this script tag should be absolutely a part of the component and not statically inserted in the head of my page.
Can anyone help me to make the magic happens? Thanks a lot in advance!
You can give react-helmet a try for managing changes to your <head> from within React components.
In particular, you can check this example where rendering the same element four times only adds the script tag once.
For completeness, the relevant code from the example (although the interesting part is to see how it executes):
import { Helmet } from "react-helmet";
function ComponentWithHeader() {
return (
<div>
<div>Oh hi</div>
<Helmet>
<script src="fake-url.js" />
</Helmet>
</div>
);
}
const App = () => (
<div>
<ComponentWithHeader />
<ComponentWithHeader />
<ComponentWithHeader />
<ComponentWithHeader />
</div>
);
You can set the state of the parent component to keep in memory that the script is already added.
if (!this.state.scriptAdded) {
// Add script tag
this.setState({ scriptAdded: true });
}

Using a regular JavaScript library inside a React component

I'm curious what's the best way to use a regular JavaScript library (not written as a React component) inside a React environment.
For example, let's say there's a JavaScript library that embeds a simple widget to my webpage. The instructions are as follows:
Include the loading tag in the header.
Embed the snippet anywhere you want.
In a normal webpage, I would do the following:
<head>
<script src="http://karaoke.com/source.js"></script>
</head>
<body>
<h1>Hello look at my cool widget library</h1>
<karaoke width="600" height="400" />
</body>
How do I achieve the same effect where I have a React component like this?
class MainView extends Component {
render() {
return (
<div>
<h1>I want to show my karaoke widget here, but how?</h1>
</div>
);
}
}
The main purpose of JSX is to feel like HTML. The main purpose of render in a React component is to render that "fake" (virtual) HTML. If your external widget is also a React component, the solution is straightforward:
class MainView extends Component {
render() {
return (
<div>
<h1>Hello look at my cool widget library</h1>
<Widget width="600" height="400" />
</div>
);
}
}
All you have to make sure is that the code above runs after your widget script is loaded (so the Widget component is present). The exact solution to this would depend on your build system.
If your external library is not a React component, then you cannot use a custom widget tag and you must render actual HTML.
The big trick is to not return from render but manually render ourselves after the widget initializes what it needs:
class MainView extends Component {
render() {
// don't render anything
return <div/>;
},
componentDidMount() {
// find the DOM node for this component
const node = ReactDOM.findDOMNode(this);
// widget does stuff
$(node).activateMyCoolWidget();
// start a new React render tree with widget node
ReactDOM.render(<div>{this.props.children}</div>, node);
}
});
Take a look at portals for more details.

React is rendering md (remarkable) as a string

Below is a dummied down version of the component I'm pulling into another component.
import React from "react"
var Remarkable = require('remarkable');
var md = new Remarkable();
const Info = (props) => {
return (
<div className="pop">
<div>
<h1>{props.title}</h1>
{md.render('# Remarkable rulezz!')}
</div>
</div>
)
}
export default Info;
On the page it is currently rendering.
(the title passed as props, as a h1, and...)
<h1># Remarkable rulezz!</h1>
So it's literally rendering out the whole thing as a string, when I want it to behave like html.
How do I do this? Or have I missed the whole point of md?
Thanks
If you for some reason need to render the html as-is using react you need to use dangerouslySetInnerHTML and wrap the content with any tag (div or span or something else)
<div dangerouslySetInnerHTML={{ __html: md.render('# Remarkable rulezz!') }} />
References:
https://facebook.github.io/react/tips/dangerously-set-inner-html.html

How to enhance a server side generated page with Aurelia.io?

I'm writing an app with some parts as SPA and some pages generated on server side for SEO. I've chosen Aurelia.io framework and I use enhance method to enable custom elements on my pages. But I can't find the best way to use aurelia specific template directives and interpolation on my server side page. Let's start with an exemple.
All of my pages contains a dynamic header. This header will be a custom element named my-cool-header. This header will load authentified user and display its name, or, if no user is currently authentified, a link to the signin will be displayed. The body of the page will be generated on server side and cached. So, we'll have something like that :
<html>
<body>
<my-cool-header>
<img src="logo.png">
<div
show.bind="user">${user.name}</div>
<div
show.bind="!user">Sign-in</div>
</my-cool-header>
<div>Cachabled content</div>
</body>
</html>
Then, my header will by defined by :
import {UserService} from './user';
import {inject} from 'aurelia-framework';
#inject(UserService)
export class MyCoolHeader {
constructor(userService) {
this.userService = userService;
}
async attached() {
this.user = await this.userService.get();
}
}
With the following template :
<template>
<content></content>
</template>
And this bootstrap script :
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.globalResources('my-cool-header');
aurelia.start().then(a => a.enhance(document.body));
}
In this configuration, the custom element is well loaded and instanciated. But, I can't access the viewModel of the node inside the <content> node. So, all the interpolation (${user.name}) and attributes (show.bind) are ignored. If I include a custom-element in my content template, it will be loaded only if it is declared as global in the bootstrap : the` tag is ignored.
I've found a workaround to be able to change the viewModel after reading the doc by setting a custom viewModel to enhance method and then, injecting it to my custom element class. Something like :
import {MainData} from './main-data';
export function configure(aurelia) {
const mainData = aurelia.container.get(MainData);
aurelia.use
.standardConfiguration()
.developmentLogging()
.globalResources('my-cool-header');
aurelia.start().then(a => a.enhance(mainData, document.body));
}
Custom element:
import {UserService} from './user';
import {inject} from 'aurelia-framework';
import {MainData} from './main-data';
#inject(UserService, MainData)
export class MyCustomElement {
constructor(userService, mainData) {
this.userService = userService;
this.mainData = mainData;
}
async attached() {
this.mainData.user = await this.userService.get();
}
}
And finally, if I change my template like that, it will work :
<html>
<body>
<my-cool-header
user.bind="user">
<img src="logo.png">
<div
show.bind="user">${user.name}</div>
<div
show.bind="!user">Sign-in</div>
</my-cool-header>
<div>Cachabled content</div>
</body>
</html>
I can't believe it is the right way to do because it's ugly and it does not resolve the problem of <require> tag. So my question is : What is the best way to do ?
Thanks to your clues, I found the solution!
Custom element need to construct its own template:
import {processContent, noView} from 'aurelia-framework';
#processContent(function(viewCompiler, viewResources, element, instruction) {
instruction.viewFactory = viewCompiler.compile(`<template>${element.innerHTML}</template>`, viewResources, instruction);
element.innerHTML = '';
return false;
})
#noView
export class MyCustomElement {
attached() {
this.world = 'World!';
this.display = true;
}
}
Then, in my view from server, we can interpolate and require custom elements!
<body>
<my-custom-element>
<require="./other-custom-element"></require>
<p
if.bind="display">Hello ${world}</p>
<other-custom-element></other-custom-element>
</my-custom-element>
</body>
I've wrote a decorator to help creating this kind of enhanced custom elements : https://github.com/hadrienl/aurelia-enhanced-template
Plus de détails en français sur mon blog : https://blog.hadrien.eu/2016/02/04/amelioration-progressive-avec-aurelia-io/
EDIT: <require> is not really working with this solution. I have to dig again :(
Change your MyCoolHeader's template from:
<template>
<content></content>
</template>
to:
<template>
<img src="logo.png">
<div show.bind="user">${user.name}</div>
<div show.bind="!user">Sign-in</div>
</template>
then change your server-generated page to something like this:
<html>
<body>
<my-cool-header></my-cool-header>
<div>Cachabled content</div>
</body>
</html>
Hope that helps. If this doesn't solve the problem or is not an acceptable solution, let me know.
Edit
After reading your reply and thinking about this a bit more I'm leaning towards removing the <my-cool-header> element. It's not providing any behavior, it only acts as a data loader, it's template is provided by the server-side rendering process and it's expected to be rendered outside of the aurelia templating system, there's no real need to re-render it. Here's what this approach would look like, let me know if it seems like a better fit:
<html>
<body>
<div class="my-cool-header">
<img src="logo.png">
<div show.bind="user">${user.name}</div>
<div show.bind="!user">Sign-in</div>
</div>
<div>Cachabled content</div>
</body>
</html>
import {MainData} from './main-data';
import {UserService} from './user';
export function configure(aurelia) {
const mainData = aurelia.container.get(MainData);
const userService = aurelia.container.get(UserService);
aurelia.use
.standardConfiguration()
.developmentLogging();
Promise.all([
this.userService.get(),
aurelia.start()
]).then(([user, a]) => {
mainData.user = user;
a.enhance(mainData, document.body);
});
}
To supplement Jeremy's answer, if you did change the template to:
<template>
<img src="logo.png">
<div show.bind="user">${user.name}</div>
<div show.bind="!user">Sign-in</div>
</template>
This content would be present when Aurelia processed the element and in the absence of a content selector, anything inside the custom element tags will be replaced by the template
If you then put your non-javascript content inside the custom element tags:
<my-cool-header>
<div>This stuff will be visible when JS is turned off</div>
</my-cool-header>
In the example above, in the absence of JS the div should still be there as Aurelia won't remove it from the DOM.
(This is of course assuming your server side tech doesn't mangle/fix the unknown HTML tags in the DOM for some reason when serving pages - which it probably won't since it would break Aurelia anyway)
EDIT:
The alternative you may be looking for is the #processContent decorator.
This allows you to pass a callback function that runs before Aurelia inspects the element.
At this point you could just lift the content between the custom element tags and add it as a child of the template element. The content should then be in scope of your viewmodel.
This way you can have the same markup in between the custom element tags with no javascript, and inside your template in the correct scope when Aurelia is running
import {processContent, TargetInstruction, inject} from 'aurelia-framework';
#inject(Element, TargetInstruction)
#processContent(function(viewCompiler, viewResources, element, instruction) {
// Do stuff
instruction.templateContent = element;
return true;
})
class MyViewModel {
constructor(element, targetInstruction) {
var behavior = targetInstruction.behaviorInstructions[0];
var userTemplate = behavior.templateContent;
element.addChild(userTemplate);
}
}
Disclaimer: the above code hasn't been tested and I pulled it from my grid which is several releases old - you may need to tweak

Categories

Resources