How to add the Tawk chat widget script to nextjs react app - javascript

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

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.

How to capture date in next js head?

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

How to return script tag in Javascript?

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

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

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>

ReactJs browser Cannot read property 'keys' of undefined

HTML code:
<div id="content"></div>
<script src="build/react.min.js"></script>
<script src="build/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-core/6.1.19/browser.min.js"></script>
<script src="ex1.jsx" type="text/babel"></script>
JSX code:
// create class
var HelloWord = React.createClass({
render: function () {
return (
<div>
<p>Hello Word!</p>
</div>
);
}
});
// show content
ReactDOM.render(
<HelloWord></HelloWord>, document.getElementById('content')
);
Console message after run:
Uncaught TypeError: Cannot read property 'keys' of undefined
Why?
I also ran into the same issue and while surfing the internet I found that there was a problem with the babel-core version that I used. I replaced that with another and got my code to work.
Try this
HTML
<div id="content"></div>
<script src="build/react.min.js"></script>
<script src="build/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script src="ex1.jsx" type="text/babel"></script>
JSX
var HelloWord = React.createClass({
render: function () {
return (
<div>
<p>Hello Word!</p>
</div>
);
}
});
// show content
ReactDOM.render(
<HelloWord></HelloWord>, document.getElementById('content')
);
It should work for you too.
Update:
You can use babel-standalone package for babel compilation with the newer version since babel-browser is deprecated.
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.25.0/babel.min.js"></script>

Categories