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>)
}
Related
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>
I am trying to access Date.now() within a script tag inside a head section. I am using the following snippet of code:-
import Link from "next/link";
import Head from "next/head";
export default function IndexPage() {
return (
<div>
<Head>
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
document.write("\x3Cscript src="https://somerandomeurl/initialize_pixel.js?v=' + Date.now() + '">\x3C/script>");`
}}
></script>
</Head>
Hello World.{" "}
<Link href="/about">
<a>About</a>
</Link>
</div>
);
}
When I run this code I get the following output:-
');
Hello World. About
How can I get the date and avoid printing '); on the screen?
Just use template strings:
<Head>
<script src={`https://somerandomeurl/initialize_pixel.js?v=${Date.now()}`}></script>
</Head>
import next/script instead of next/head.
import Script from 'next/script'
and use it
<Script src={`https://somerandomeurl/initialize_pixel.js?v=${Date.now()}`}/>
Can try this
document.write(
"<script src='https://somerandomeurl/initialize_pixel.js?v=" +
Date.now() +
"'></script>"
);
I am trying to return a script tag in javascript.
export const MarketData = () => {
return (
<>
<p>
Market Data
</p>
{/* Script tag here */}
</>
)
}
The script tag looks like this:
<script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-market-quotes.js" async>
...
</script>
Full code I am trying to embed can be found at: https://www.tradingview.com/widget/market-overview/
How should I go about accomplishing this?
Thanks
How can I get JSON data embedded in a script tag?
<!DOCTYPE html>
<html>
<head>
<script id="data" type="application/json">{org: 10, items:['one','two']}</script>
<script type="text/javascript">
var obj = JSON.parse( document.getElementById('data').value );
console.log( obj );
console.log( obj.org );
</script>
</head>
<body>
</body>
</html>
I'm getting:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
<script> elements are not form controls. They don't have value properties (so. when you read it, you get undefined which is "undefined" when cast to a string, and that isn't valid JSON).
Read the content of the text node inside the element instead.
You also need to write JSON instead of a JavaScript object literal.
Property names must be strings, not identifiers.
Strings must be quoted with " not '.
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
<script type="text/javascript">
var obj = JSON.parse(document.getElementById('data').firstChild.data);
console.log(obj);
console.log(obj.org);
</script>
The u comes from "undefined". Try:
JSON.parse( document.getElementById('data').innerHTML );
...but keep in mind that your current input is not JSON. So correctly formatted it would be:
<script id="data" type="application/json">{"org":10,"items":["one","two"]}</script>
I have a javascript method which is receiving a UTF-8 encoded string (ViewBag.errorText), and uses this as a parameter to a new function.
The problem is that the text displayed in show_error_dialog is displaying the html escaped characters (æø etc') and not the intended ("æåø" etc.).
I presume the problem is the enclosed <text> tags but can't seem to get around this.
<script type="text/javascript" charset="utf-8">
function performLoadOperations() {
#if(ViewBag.errorText!= null) {
<text>show_error_dialog('#ViewBag.errorText');</text>
}
}
</script>
I think all Razor-inserted text is HTML-encoded by default. Use Html.Raw() to pass the string unencoded.
<script type="text/javascript" charset="utf-8">
function performLoadOperations() {
#if(ViewBag.errorText!= null) {
<text>show_error_dialog('#Html.Raw(ViewBag.errorText)');</text>
}
}
</script>
Use:
#Html.Raw(Ajax.JavaScriptStringEncode(Model))
to safely insert values into javascript
just use javascript escape function:
function encode_utf8( s )
{
return unescape( encodeURIComponent( s ) );
}
function decode_utf8( s )
{
return decodeURIComponent( escape( s ) );
}
I'm not sure but i think there was unescape() function with js. Try to pass your text with it. It might help