This question already has answers here:
Convert a React.element to a JSX string
(4 answers)
Closed 1 year ago.
How would I take HTML stored in a variable and convert it into a string?
Take this:
var html = <div>html</div>;
And Make it into this:
var html = "<div>html</div>"
As per the flagged duplicate you can use ReactDOMServer.renderToString(element), or ReactDOMServer.renderToStaticMarkup(element) to render a react element as an HTML string (renderToStaticMarkup() doesn’t render the extra DOM attributes that React uses internally, such as data-reactroot).
Both methods can be used in both the server and browser environments.
function App() {
const html = (<div>html</div>);
return (
<div>
{ReactDOMServer.renderToStaticMarkup(html)}
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react#17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom-server.browser.production.min.js"></script>
<div id="root"></div>
You can get the element's outerHTML property:
var elem = document.querySelector('div');
var res = elem.outerHTML;
console.log(JSON.stringify(res))
<div>html</div>
Related
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.
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>
I am working on a React app which needs json-ld schema to be defined. I get the schema string through an API and need to add the appropriate script tag to my page.
My schema string looks something like this:
[{"#context": "http://schema.org"}]
I expect this to be translated to:
<script type="application/ld+json">
[{"#context": "http://schema.org"}]
</script>
However, I am having trouble dealing with the double quotes, as these get converted to html equivalent - "
This is how my code looks like:
schemaString = "[{\"#context\": \"http://schema.org\"}]";
render() {
return (<div>{schemaString &&
<script type="application/ld+json">
{schemaString}
</script>}
</div>)
}
The html generated is:
<div>
<script type="application/ld+json">
[{"#context": "http://schema.org"}]
</script>
</div>
Any pointers on what I am missing here? Thanks!
Am I late? :) Make sure you place the script tag content by dangerouslySetInnerHTML property. Also, don't forget to convert default object into proper JSON by JSON.stringify() method.
Like this:
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(yourSchemaObject) }}
/>
);
schemaString = [{ "#context": "http://schema.org" }];
render() {
return (
<div>
{schemaString &&
<script type="application/ld+json">
{JSON.stringify(schemaString)}
</script>
}
</div>)
}
This question already has answers here:
Template literals like 'some ${string}' or "some ${string}" are not working
(7 answers)
Closed 5 years ago.
I'm learning React using a textbook and the string replacer ${} from this particular example doesn't work and can't figure out why. I've double checked any typos to make sure. Other examples from the book has worked fine so far.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Hello extends React.Component {
constructor (props) {
super(props)
this.clickHandler = this.clickHandler.bind(this) //isolates 'this' of Hello class from other 'this'
}
clickHandler (e) {
const name = this.props.name
window.alert('Hello, ${name}') //!!this doesn't work....
}
render () {
return (
<div onClick={this.clickHandler}>Say Hello</div>
)
}
}
ReactDOM.render((<Hello name="Johnny" />),document.getElementById("root"))
</script>
</body>
</html>
use back-tick
window.alert(`Hello, ${name}`)
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.