Using a regular JavaScript library inside a React component - javascript

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.

Related

Render HTML of embed-deployed Component

I want to integrate my react app to a 3rd party app which enables me to put a script that appends the elements into the html.
But it appears that it is not that straightforward in react. The script does not append the elements so my custom component does not appear on the page.
This is what I am trying to do ( but not a gist ):
function Snippet){
return (
<Wrapper>
<h1> Snippet 1</h1>
<script src="https://gist.github.com/xxxx/e4208e452e32e353b6076944c80a1058.js"></script>
</Wrapper>
)
}
Is there a way to do this with just react?
Hi Going back to this inquiry, I found an npm package that enables the embedding of github gist in a react component.
Following the implementation of the Gist Component in the package, we can also deploy the code programmatically instead of pasting the deployment script directly to the component and it will work just fine.
export default class DeployedComponent extends React.Component{
constructor(props){
super(props);
}
componentDidMount(){
(function(props,doc,elementName,id){
let jsElement;
if(doc.getElementById(id)){
return;
}
jsElement = doc.createElement(elementName);
jsElement.id = id;
jsElement.src= "deployment_script_src";
doc.getElementsByClassName("cb-deployment-wrapper")[0].appendChild(jsElement);
})(this.props, document,"script","script_id");
}
render(){
return (
<div className="w-100 cb-deployment-wrapper ">
</div>
);
}
}

Infogram embed code not rendering in React

I have the following embed code from infogram which is not rendering on my react app.
code looks as below:
<div class="infogram-embed" data-id="861ca70e-552c-4a4f-960a-4c7e7ff62881" data-type="interactive" data-title="Step by Step Charts"></div><script>!function(e,t,s,i){var n="InfogramEmbeds",o=e.getElementsByTagName("script")[0],d=/^http:/.test(e.location)?"http:":"https:";if(/^\/{2}/.test(i)&&(i=d+i),window[n]&&window[n].initialized)window[n].process&&window[n].process();else if(!e.getElementById(s)){var r=e.createElement("script");r.async=1,r.id=s,r.src=i,o.parentNode.insertBefore(r,o)}}(document,0,"infogram-async","https://e.infogram.com/js/dist/embed-loader-min.js");</script><div style="padding:8px 0;font-family:Arial!important;font-size:13px!important;line-height:15px!important;text-align:center;border-top:1px solid #dadada;margin:0 30px">Step by Step Charts<br>Infogram</div>
I am using a html parsing library for react which works perfectly fine in all other cases.
Any idea why this is not working?
Thanks
Not sure if this helps, here is how I made it work with React
https://jsfiddle.net/wonderwhy_er/4dt28xzL/6/
Or code
In HTML
<script>!function(e,t,s,i){var n='InfogramEmbeds',o=e.getElementsByTagName('script')[0],d=/^http:/.test(e.location)?'http:':'https:';if(/^\/{2}/.test(i)&&(i=d+i),window[n]&&window[n].initialized)window[n].process&&window[n].process();else if(!e.getElementById(s)){var r=e.createElement('script');r.async=1,r.id=s,r.src=i,o.parentNode.insertBefore(r,o)}}(document,0,"infogram-async","https://e.infogram.com/js/dist/embed-loader-min.js");</script>
<div id="app"></div>
In JS
class App extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<div class="infogram-embed" data-id="861ca70e-552c-4a4f-960a-4c7e7ff62881" data-type="interactive" data-title="Step by Step Charts">
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
I moved script part away, it just requests a loader from Infogram and you do not need to do it inside of React render, so I just moved it to header of page or something.
You also have something else at the end of the embed which I remeved and it works. Check link.

Parse and Render external HTML in React component

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"));

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 });
}

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