Access variables defined in <head> or external script from React component - javascript

I am integrating a third-party library into my React app.
They provide this script I need to add to my <head>:
index.html
<head>
<script>
var externalVariable1 = externalVariable1 || {};
var externalVariable2 = externalVariable2 || {};
</script>
// tag.min.js gives value to these variables
<script async src="//example.com/tag.min.js"></script>
</head>
I need to use access these two variables from my component. I tried the following but I get 'externalVariable1' is not defined error. Any thoughts?
MyScreen.js
import React from 'react';
const MyScreen = () => {
return (
<React.Fragment>
<div>
<h2>Hello!</h2>
</div>
<div id='myId'>
{externalVariable.push(function() { externalVariable2.display();})}
</div>
</React.Fragment>
);
}
export default MyScreen;

If you want to access variables defined in the global scope from inside of a React component, you can typically do that by accessing the variable through the window object.
See the example below:
function App(){
return <h1>The secret is {window.secret}</h1>
}
ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<!-- Adding some global variables outside of React -->
<script>
var secret = "hello";
</script>
<div id="root"></div>

Related

Embed SharpSpring form into React component

I'm trying to embed a Sharpspring form script into my React (page.jsx) component. For this form to load succesfully it needs to be placed outsite the <head></head> element, and inside the <div> where I want to display the form.
The original HTML code I need to embed looks like this:
<!-- SharpSpring Form -->
<script type="text/javascript">
var ss_form = {'account': 'MzawMDE3tzQzBQ', 'formID': 'szBIMrFMSzbXTUm0TNM1MTc107VMNbfQTTRJTExOTUoySk4zAA'};
ss_form.width = '100%';
ss_form.domain = 'app-3QNK98WC9.marketingautomation.services';
// ss_form.hidden = {'field_id': 'value'}; // Modify this for sending hidden variables, or overriding values
// ss_form.target_id = 'target'; // Optional parameter: forms will be placed inside the element with the specified id
// ss_form.polling = true; // Optional parameter: set to true ONLY if your page loads dynamically and the id needs to be polled continually.
</script>
<script type="text/javascript" src="https://koi-3QNK98WC9.marketingautomation.services/client/form.js?ver=2.0.1"></script>
I'm trying to embed it into page.jsx this way:
import React from "react";
function myComponent() {
var ss_form = {'account': 'MzawMDE3tzQzBQA', 'formID': 'szBIMrFMSzbXTUm0TNM1MTc107VMNbfQTTRJTExOTUoySk4zAAA'};
ss_form.width = '100%';
ss_form.domain = 'app-3QNK98WC9Y.marketingautomation.services';
return (
<main>
<div className="form">
{ss_form}
<script src="https://koi-3QNK98WC9Y.marketingautomation.services/client/form.js?ver=2.0.1" type="text/javascript" />
</div>
</main>
);
}
export default myComponent;
However, I get this error:
Error: Objects are not valid as a React child (found: object with keys {account, formID, width, domain}). If you meant to render a collection of children, use an array instead.
I know I'm supposed to use "arrays instead" but I could not find any documentation that solved this error. Any suggestions on how I could make this embed code to work?
Thank you.
I was able to embed the form using helmet.
First installed:
npm install helmet
My working code looks like this:
import React from "react";
import ReactDOM from "react-dom";
import { Helmet } from 'react-helmet';
function myComponent() {
return (
<main>
<Helmet>
<script
src="https://koi-3QNK98WC9.marketingautomation.services/client/form.js?ver=2.0.1"
/>
<script>
{`
var ss_form = {'account': 'MzawMDE3tzQzBQ', 'formID': 'szBIMrFMSzbXTUm0TNM1MTc107VMNbfQTTRJTExOTUoySk4zAA'};
ss_form.width = '100%';
ss_form.domain = 'app-3QNK98WC9Y.marketingautomation.services';
ss_form.target_id = 'form';
ss_form.polling = true;
`}
</script>
</Helmet>
<div id="form"> </div>
</main>
);
}
export default myComponent;
Turns out SharpSpring embed code supports the variant ss_form.target_id, which displays the form on the designated ID.
I'm sure the above solution will work for other javascripts and embed codes as well.

Why isn't html running javascript I import when I use import-export

My code works fine when I add my module straight into the html code, but it won't load it when I try to first import the module to a different javascript file.
I've tried exporting everything, from my module.
HTML:
<html>
<head>
<title>
Hello world
</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Tradingpost, done by no css gang.</h1>
<div id="sidenav">Here be the links to other pages</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script src="js/app.js"></script>
</body>
</html>
app.js:
import * as sidebar from "./visualModules/sidebarmodule"
function cumulator() {
sidebar.createSidebar()
}
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
It should add elements to the div. But it wont do it unless I straight up use the sidebarmodule.js. I want to do it through the app.js
EDIT
Found the problem!
Didn't initialize index in the for loop.
EDIT2
And the type="module" which needed to be added
When you load your app.js in your html file, try to add:
<script type="module" src="js/app.js"></script>
That should work when you want to use ESModules. But please update us regardless :)
Update:
Ok after creating a project myself using your HTML and JS, I found a few errors.
First: When using ESModules, you can't use any functions in the JS through your HTML, you will have to inject everything from the app.js.
index.html:
<body>
<div id="sidenav">
Here be the links to other pages
</div>
<br>
<footer id="footer">
Done whenever. Copyright is mine.
</footer>
<script type="module" src="js/app.js"></script>
app.js:
import { createSidebar } from './visualModules/sidebarmodule.js';
cumulator();
function cumulator() {
createSidebar()
}
Notice two things: at the end of the import, since we are not using a compiler, the modules do not recognize files without their extension. So I had to add .js to sidebarmodule. Secondly, I had to invoke cumulator function within the app.js file (like I said earlier, you cannot use any module functions outside their scope. There are no global variables with ESModules).
sidebarmodule.js:
function sidebarAdder(pages) {
const sidebar = document.getElementById("sidenav")
const list = document.createElement("UL")
for(var index = 0; index < pages.length; index++) {
const ul = document.createElement("LI")
const a = document.createElement("A")
a.setAttribute("href", "/" + pages[index])
a.innerHTML = "" + pages[index]
ul.appendChild(a)
list.appendChild(ul)
}
sidebar.appendChild(list)
}
export function createSidebar() {
var pages = [
"home",
"tradingpost"
]
sidebarAdder(pages)
}
You did not declare index inside your for loop, so I just added a var.
Hope this helps.
import is asynchronous in Javascript (in a browser, not Node.js) so you're calling createSidebar() before the module is loaded. You can use import to return a promise so you can execute code once it is completed.
Remove the embedded Javascript from your html, but leave the link to app.js. Then change app.js to this...
import("./visualModules/sidebarmodule")
.then((sidebar) => {
sidebar.createSidebar();
});

How to code JavaScript function method returned by react component

I'm, working on server-side rendering in a React app and I have the following JavaScript code. My <FullPage action={this.handler}/> component has an action property that is set to a function. When that function gets called, I want to set a variable (or even some state) in this component here. I can't figure out how to declare handler
export default (req) => {
var myVar =
<Router location={req.path} context={{}}>
<FullPage action={this.handler}/>
</Router>
const content = renderToString(
myVar
);
return `
<html>
<head>
<link rel="stylesheet" href="App.css">
</head>
<body>
<div id="root">${content}</div>
<script src="bundleclient.js"></script>
</body>
</html>
`;
};

Dynamically load JSX file in JavaScript

I am trying to implement a wrapper API file for a ReactJS component.
For example, /js/test.react.js
/** #jsx React.DOM */
var TESTCLASS = React.createClass({
render : function() {
return (
<div> Test </div>
);
}
});
I have written a wrapper JavaScript file for that:
var testClass = {
load: function () {
var script = document.createElement("script");
script.type = "text/jsx";
document.head.appendChild(script);
script.onload = function(){
React.render(
<TESTCLASS/>,
document.body)
};
script.src ="./js/test.react.js";
}
};
Then I can use the wrapper API JavaScript in a third-party HTML.
<html>
<head>
<title>Hello React</title>
<script src="http://fb.me/react-0.12.2.js"></script>
<script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/jsx" src="test.js"></script>
</head>
<body>
<div id="content"></div>
<script>
testClass.load();
</script>
</body>
</html>
However, it seems to me /js/test.react.js cannot be dynamically loaded as pure JavaScript file. Can any expert explain to me the reason and provide a proper solution to write my wrapper API JavaScript file?
JSXTransformer*.js exports a global JSXTransformer object which has an exec() function, which transpiles JSX then eval()s the result.
You could try running JSXTransformer.exec() with the script's contents onload first.
Also, FYI, the #jsx pragma is no longer required as of React 0.12 :)

HTMl Import own WebComponent

In my index.html I import an external HTML file with an Template, Shadow DOM etc. A custom web Component.
// index.html
...
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.4/platform.js"></script>
<link rel="import" href="/html-components/userlogin-header.html" >
<head>
<body>
<userlogin-header username="Test User"userimage="http://domain.com/img.jpg"></userlogin-header>
...
And the other file userlogin-header.html:
// userlogin-header.html
<template id="userlogin-header">
<div class="imgbox">
<img src="" class="userimage">
</div>
<div class="userinfo">
<div class="name"><span class="username"></div>
</div>
</template>
<script>
var doc = this.document.currentScript.ownerDocument,
UserLoginProto = Object.create( HTMLElement.prototype );
UserLoginProto.createdCallback = function() {
var template = doc.querySelector( "#userlogin-header" ),
box = template.content.cloneNode( true );
this.shadow = this.createShadowRoot();
this.shadow.appendChild( box );
var username = this.shadow.querySelector( '.userinfo .username' );
username.innerHTML = ( this.getAttribute( 'username' ) || 'Unbekannt' );
var imageurl = this.shadow.querySelector( 'img.userimage' );
imageurl.src = 'https://secure.gravatar.com/avatar/' + this.getAttribute( 'userimage' ) + '1?s=40&d=http://s3-01.webmart.de/web/support_user.png';
};
var Xuserlogin = doc.registerElement( 'userlogin-header', { 'prototype' : UserLoginProto } );
</script>
The problem is that there is the following error on call index.html
Uncaught TypeError: Cannot read property 'content' of null
If I enable HTML Import in my Chrome everything works correctly. But then I disable this and use platform.js instead there is this error.
Is there any solution for this problem? I do not want to use the whole polymer framework.
This is a symptom of this caveat of the polyfill.
In a native HTML Imports, document.currentScript.ownerDocument
references the import document itself. In the polyfill use
document._currentScript.ownerDocument (note the underscore).
Once you change that, you also need to use document.registerElement instead of doc.registerElement. You want to register the element such that it's visible to the importing document, not the imported one.
var Xuserlogin = document.registerElement(...);
Here's a working plunk.

Categories