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>"
);
Related
I'm trying to figure out how to add a chat widget from Tawk to a next.js react app.
In my _app.js, I have added the script import tag and tried to set the widget as follows:
import Script from 'next/script'
{/* <!--Start of Tawk.to Script--> */}
<Script id="tawk" strategy="lazyOnload">
dangerouslySetInnerHTML={{
__html: `
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/[]/[]';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
`,
}}
</Script>
When I try this, I get an error that says:
Unhandled Runtime Error SyntaxError: Unexpected identifier
Call Stack loadScript ../../node_modules/next/dist/client/script.js
(148:18) eval ../../node_modules/next/dist/client/script.js (167:62)
I contacted the tawk dev support team, who acknowledged an issue with react, and suggested that a fix had been pushed with a new version 2.0.1 heres the link
https://www.npmjs.com/package/#tawk.to/tawk-messenger-react
When I try that both in _app.tsx and _document.tsx, I get more than 10 errors with that package.
Has anyone figured out how to use tawk in a next.js react app?
I made a working project with a real Tawk.to account:
https://codesandbox.io/s/tawk-test-ovmsqy?file=/pages/_app.js
You should change the ids at s1.src line!
import Script from "next/script";
function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
<Script id="tawk" strategy="lazyOnload">
{`
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/62f4b8c537898912e962654a/1ga5v3hhr';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
`}
</Script>
</>
);
}
export default MyApp;
The problem is that dangerouslySetInnerHTML is outside the tag you have it like this:
<Script id="tawk" strategy="lazyOnload">
dangerouslySetInnerHTML={{
should be:
<Script id="tawk" strategy="lazyOnload" dangerouslySetInnerHTML={"your data"} />
However, it is best to include the code inside the tag. Your _app.js should look like this:
import "../styles/globals.css";
import Script from "next/script";
function MyApp({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
{/* <!--Start of Tawk.to Script--> */}
<Script id="tawk" strategy="lazyOnload">
{`
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/[]/[]';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
`}
</Script>
</>
);
}
export default MyApp;
you should be able to create a twik.js file in the public folder and load it with next/script without any issues
For cleaner approach you can use #tawk.to/tawk-messenger-react at NPM
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>
Am just starting with Vue.js and ui development, and I am trying to make a very simple vue.js call. However, when I am launching my html page using liveserver on Visual Studio Code no JavaScript function is getting called from app.js. I cant figure out what is wrong with the code.
Can someone please advise?
Vue included in HTML-
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vue Basics</title>
<link
href="https://fonts.googleapis.com/css2?family=Jost:wght#400;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="styles.css" />
<script src="https://unpkg.com/vue#next" defer></script>
<script src="app.js" defer></script>
app.js code -
function getRandomValue(min, max){
return Math.floor(Math.random() * (max - min)) + min;}
const app = Vue.createApp({
data(){
return{
playerHealth:100,
monsterHealth:100
};
},
methods:{
attackMonster(){
console.log('attack called')
const attackValue = getRandomValue(5,12);
this.monsterHealth = this.monsterHealth - attackValue;
this.attackPlayer()
},
attackPlayer(){
console.log('attack Player called')
const attackValue = getRandomValue(8,15);
this.playerHealth = this.playerHealth - attackValue;
}
}
});
You need to mount your app to a <div> tag, for example:
In your html:
<div id="app"></div>
In app.js:
const vm = app.mount('#app')
Here is the detailed explanation from Vue.js documentation:
https://v3.vuejs.org/guide/instance.html#creating-an-application-instance
You have defined methods attackMonster and attackPlayer but you didn't call them. You can use created() to call them or you can also use mounted() (if you need to access DOM).
created () {
this.attackMonster();
}
Also you need to mount Vue app to HTML.
const app = Vue.createApp({
/** the rest of your vue app */
/** the rest of your vue app */
created () {
this.attackMonster();
}
})
const vm = app.mount('#app');
html
<body>
<div id="app">
<p>playerHealth: {{ playerHealth }}</p>
<p>monsterHealth: {{ monsterHealth }}</p>
</div>
</body>
Please check the path in your script tag
<script src="/path/to/app.js" defer></script>
I have a html template like
<!doctype html>
<html lang="en">
<head>
</head>
<body>
</body>
some body
<script type="text/javascript">
**Some JQUERY**
</script>
</body>
</html>
I am trying to convert it into react functional component.Everything is done But in the script tag there is some JQUERY written for one of the elements in the body.
Can anyone tell me how to implement this jquery in my component or any way to convert the functions in script tag into javascript functions??
You can do this by using react functional component or by using react hooks.
Example:
import React, {useEffect, useState} from "react";
import * as $ from "jquery";
const HtmlToReact = () => {
const [loaded, setLoaded} =useState(false);
useEffect(() => {
if (!loaded) {
setLoaded(true);
// ... jquery//;
}
},[loaded]);
return (
<body>
//statement
</body>
)
}
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>)
}