I am going to show embed tweet data on the react project.
In publish.twitter.com, they show that publish code about embed tweet.
<a class="twitter-timeline" href="https://twitter.com/twitterDev?ref_src=twsrc%5Etfw" data-tweet-limit="3">Tweets by twitterDev</a>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
But in react project, it doesn't work, only shows <a>tag -Tweets by twitterDev.
Please help me.
Please try with following.
React.useEffect(() => {
const script = document.createElement("script");
script.setAttribute("src", "https://platform.twitter.com/widgets.js");
document.getElementsByClassName("lists")[0].appendChild(script);
}, []);
<a class="twitter-timeline" href="https://twitter.com/twitterDev?ref_src=twsrc%5Etfw" data-tweet-limit="3">Tweets by twitterDev</a>
Hope to your business will be good.
Related
The following code is required to be injected into the head for Sovrn display ads:
<script type="application/javascript">var googletag=googletag||{};googletag.cmd=googletag.cmd||[];googletag.cmd.push(function(){googletag.pubads().disableInitialLoad()});</script><script type="application/javascript" src="//ap.lijit.com/www/headerauction/headersuite.min.js?configId=XXXX"></script>
It looks for a div with ID="21728840" to display an ad for that div. I'm using Netlify so injecting this script into the head is not an issue, but Netlify does this post-process. Therefore, by the time, the script loads, it is not able to find the ID since the element is not defined, and returns a 403 error. I looked at many suggestions, and tried to use useEffect in the file where the ad is like so:
export const BlogIndexTemplate = ({ posts, title...
...
useEffect(() => {
var googletag = googletag || {}
googletag.cmd = googletag.cmd || []
googletag.cmd.push(function() {
googletag.pubads().disableInitialLoad()
})
const script = document.createElement('script')
script.async = true
script.src =
'//ap.lijit.com/www/headerauction/headersuite.min.js?configId=XXXX'
document.head.appendChild(script)
}, [])
...
{!!posts.length && (
<section className="section">
<div className="container">
<PostSection posts={filteredPosts} />
</div>
</section>
)}
The ad container is located in PostSection like so:
class PostSection extends React.Component {
...
<div className="sidebar-sticky-container">
<div className="ad-skyscraper-container sticky-widget">
<div id="21728840"></div>
I'm not sure what other approach I could try to get the script injected, and manipulate the div with ID 21728840 to display the ad.
After a lot of research, I discovered that using useEffect and most of the suggestions online are unnecessary for Gatsby. To inject a 3rd party script, one needs to create a gatsby-ssr.js file in the root directory. Inside this file, one should have the following for a basic set up:
const React = require('react')
exports.onRenderBody = function({
setHeadComponents,
setPreBodyComponents
}) {
setHeadComponents([
<script
dangerouslySetInnerHTML={{whateveryouneedtoset}}>
])
setPreBodyComponents([
<script
dangerouslySetInnerHTML={{whateveryouneedtoset}}>
])
}
All options for using the gatsby-ssr.js file can be found here: Gatsby SSR
I've been trying to connect my AdSense account with my Gatsby blog and it seems impossible. AdSense is asking me to place this code between the head tag of my html
<script data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
I've tried gatsby adsense plugins and other things and AdSense keeps telling me the code is not in the website. Since the website is hosted in S3, I downloaded the generated index.html and changed the code and re uploaded it. I think the problem is due to an added attribute called data-checked-head to the script tag, so even though I add the code above, what I see in the browser is this:
<script data-ad-client="ca-pub-XXXXXXXXXXXXXXXX" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" data-checked-head="true"></script>
If this code is what AdSense sees, then of course he doesn't recognize it. Does anyone know what can I do in this case?? Or why is this attribute even there?? Thanks
I can't answer about the details of AdSense but I have had problems with meta tags in the head of HTML myself. Here's two possibilites to debug your code in regards to Gatsby:
Many plugins are disabled by default in development mode. Try gatsby build and gatsby serve and then check if it works with plugins.
Use react-helmet to place your script tag in the head of HTML. Use gatsby build and gatsby serve for testing this as well.
You can use gatsby-plugin-google-adsense for displaying ads on your site.
The best way I found is from this article, which suggest a simple React implementation of Google AdSense.
In your gatsby-ssr.js file:
const React = require('react')
const HeadComponents = [
<script
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXX"
crossOrigin="anonymous"
async
/>,
]
exports.onRenderBody = ({ setHeadComponents }, pluginOptions) => {
setHeadComponents(HeadComponents)
}
Then you create a Banner component to include in your Gatsby.js pages:
const Banner: React.FC<BannerProps> = ({
className,
style,
layout,
format,
client = 'ca-pub-XXXX',
slot,
responsive,
layoutKey,
}) => {
useEffect(() => {
try {
const adsbygoogle = window.adsbygoogle || []
adsbygoogle.push({})
} catch (e) {
console.error(e)
}
}, [])
return (
<div className="banner-container">
<ins
className="adsbygoogle"
style={style}
data-ad-layout={layout}
data-ad-format={format}
data-ad-client={client}
data-ad-slot={slot}
data-ad-layout-key={layoutKey}
data-full-width-responsive={responsive}
/>
</div>
)
}
Full article here.
The example is I have an external library such as Materialize.js, the components I need to render depend on it, what is the best way to include this library? The documentation of ReactJS refers to "Code Splitting" which I have done with my own JavaScript but cannot do with an external minimized script. What approach yields the highest performance?
I have tried the following
componentDidMount() {
const script = document.createElement("script");
script.src = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js";
script.async = true;
script.onload = () => this.scriptLoaded();
document.body.appendChild(script);
}
scriptLoaded = async () => {
this.setState({materializeJsLoaded: true});
}
I have also then also tried including it in the index.html page at the bottom of the body tag.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
Here is an article that discusses creating a custom css build and importing javascript on a per-component basis:
https://medium.com/#mattdlockyer/youre-using-materialize-css-wrong-470b593e78e9
The following tsx code generates TypeScript errors. //#ts-ignore doesn't work.
<Helmet>
<script>
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-*******');
</script>
</Helmet>
The following code works, but I would like to use a child <script> tag vs the script component property.
<Helmet
script={[
{
type: 'application/javascript',
innerHTML: '(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({\'gtm.start\':new Date().getTime(),event:\'gtm.js\'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!=\'dataLayer\'?\'&l=\'+l:\'\';j.async=true;j.src=\'https://www.googletagmanager.com/gtm.js?id=\'+i+dl;f.parentNode.insertBefore(j,f);})(window,document,\'script\',\'dataLayer\',\'GTM-*******\');'
}
]}
/>
Figured it out thanks to https://github.com/nfl/react-helmet/issues/334#issuecomment-413319383.
<Helmet>
<script>
{`
alert('BOOM');
`}
</script>
</Helmet>
Does this script have to be embedded as part of your Component heap?
I faced a similar issue when using YouTube's iframe API and the solution was to create the script element and reference the javascript objects created once they exist (if you need to do that, looks like you literally just want to import some JS). I didn't need to create a react component for this unless there were visual elements I wanted to manage.
// GoogleTagManager.ts
export class GoogleTagManager {
someVariable: someVariableType = null
constructor () {
const script: HTMLScriptElement = <HTMLScriptElement>document.createElement('script')
script.src = '[URL_TO_JS_FILE]'
script.onload = (): void => console.log('loaded google tag manager')
document.body.appendChild(script)
}
WaitForVariable (): void {
let timeout: number
const OnTimeout = (): void => {
if (timeout) {
clearTimeout(timeout)
}
if (typeof [TARGET_VARIABLE] !== 'undefined') {
this.someVariable = [TARGET_VARIABLE]
return
}
timeout = setTimeout(OnTimeout, 1000)
}
}
}
If you want to display some information then you could turn this into a React Component and move the constructor logic to componentDidMount. Alternatively I would consider sending any resultant data to a store and having a separate component for rendering the resultant data.
With caution, you can use dangerouslySetInnerHTML like so:
<script
dangerouslySetInnerHTML={{
__html: `
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-*******');
`,
}}
/>
But be careful of cross-site scripting (XSS) attacks.
Has any one of you successfully integrate Moengage in ReactJs ? I have try it by put this inside <head> tag on index.html of HTMLWebpackPlugin's template.
<script type="text/javascript">
(function(i,s,o,g,r,a,m,n){
i['moengage_object']=r;t={}; q = function(f){return function(){(i['moengage_q']=i['moengage_q']||[]).push({f:f,a:arguments});};};
f = ['track_event','add_user_attribute','add_first_name','add_last_name','add_email','add_mobile',
'add_user_name','add_gender','add_birthday','destroy_session','add_unique_user_id','moe_events','call_web_push','track','location_type_attribute'];
for(k in f){t[f[k]]=q(f[k]);}
a=s.createElement(o);m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m);
i['moe']=i['moe'] || function(){n=arguments[0];return t;}; a.onload=function(){if(n){i[r] = moe(n);}};
})(window,document,'script','https://cdn.moengage.com/webpush/moe_webSdk.min.latest.js','Moengage');
</script>
I put the moengage's config in a file called 'moengage.js'. So i can easily import & use it in another files.
export const Moengage = moe({
app_id:"APP ID",
debug_logs: 0
});
Then, i use it in another file
import { Moengage } from '../config/moengage.js'
...
Moengage.track_event('Loan_Data', {
'loan_name': 'Example name',
'loan_type_id': 123,
})
Unfortunately, mine doesn't work. Did you ever try moengage on ReactJs ? Any help would be great. Thank you
The variable moe is available in the window and thus putting it in a config file will not work. The initialization script has to be placed in the <head> tag.
You can access the moe variable through the window wherever required. In your config file you can try something like this:
export const Moengage = window.moe({
app_id:"APP ID",
debug_logs: 0
});
PS. I develop the Web SDK at MoEngage. Please feel free to reach out to us at support#moengage.com for any further queries.