Adding a 3rd Party Ad Script to a React App - reactjs

I received an Ad Script that i need to include in my react app. The script tag runs in the body of the code and should load an image.
This is the tag im trying to insert.
<script type="text/adtag">
<ins class='dcmads' style='display:inline-block;width:300px;height:250px'
data-dcm-placement='N6246.289102DENTALPRODUCTSHOPPER/B27429766.334458108'
data-dcm-rendering-mode='script'
data-dcm-https-only
data-dcm-gdpr-applies='gdpr=${GDPR}'
data-dcm-gdpr-consent='gdpr_consent=${GDPR_CONSENT_755}'
data-dcm-addtl-consent='addtl_consent=${ADDTL_CONSENT}'
data-dcm-ltd='false'
data-dcm-resettable-device-id=''
data-dcm-app-id=''>
<script src='https://www.googletagservices.com/dcm/dcmads.js'></script>
</ins>
</script>
<script language="javascript" type="text/javascript" src="https://cdn.doubleverify.com/dvbs_src.js?ctx=2974662&cmp=27429766&plc=334458108&sid=7942714&dvregion=0&unit=300x250">
</script>
Ive tried creating a component that inserts the tag as a child of a div
function Script(props) {
const ref = useRef()
useEffect(() => {
if (ref.current) {
const fragment = document.createRange().createContextualFragment(`<div>${props.innerHTML}</div>`)
ref.current.appendChild(fragment)
}
}, [ref])
return <div ref={ref} />
}
And I've tried a few other things like using dangerouslysetinnerhtml but nothing seems to work.
If Successful the below image shows the code that should be inserted into the body.
expected result
Any help would be appreciated.

Related

I am new to React and need some assistance regarding How can I embed a live video stream in react with following streaming code

This is a script written in JavaScript that uses the JSMpeg library to display a video stream from a WebSocket server at the URL "ws://local-server:PORT". It also uses JQuery to measure the latency (or delay) of the video stream. The latency measurement is performed by setting an image source to the URL "http://local-server:PORT" and measuring the time it takes to receive a response (or an error) from the server. The latency measurement is repeated every 500ms by calling the "latency" function with the setTimeout method. The latency measurement is displayed in a element with the id "timer".
Following is the code (from backend):
<html>
<body onload="latency()">
<canvas id="canvas"></canvas>
<br>
<div>
<h1 style="color:black"><img id="junkOne" />Lantency (Client->Server):
<p id="timer"></p>
</h2>
</div>
</body>
<script src="https://cdn.jsdelivr.net/jsmpeg-player.min.js"></script>
<script src="http://ajax.googleapis.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
player = new JSMpeg.Player('**ws**'://local-server:PORT', {
canvas: document.getElementById('canvas') // Canvas should be a canvas DOM element })
</script>
<script>
function latency() {
var start = new Date().getTime();
$('#junkOne').attr('src', '**http**://local-server:PORT').error(function() {
var end = new Date().getTime();
$('#timer').html("" + (end - start) + "ms");
});
setTimeout(latency, 500);
}
</script>
So, a live video stream is coming and I can see it by pasting this link ('http://local-host:PORT') in the browser, But I am unable to fetch this video in react for client.
I have tried different option like HTML video elements, React HLS library, React canvas but I can not embed this streaming in react.
import React, { useRef, useEffect, useState } from 'react';
import JSMpeg from 'jsmpeg-player';
const VideoStream = () => {
const videoRef = useRef(null);
const [videos, setVideos] = useState()
useEffect(() => {
new JSMpeg.Player(`http://host:PORT/`, {
canvas: videoRef.current,
});
}, []);
return <>
<canvas ref={videoRef} />
</>
}
export default VideoStream;

Setup Pinterest tag with Google Tag Manager doesn't work

I followed Pinterest steps to implement Pinterest tag on my Next.js website.
This is a no code implementation, I have Google Tag successfully installed on my website and I can see the events fired on the tag assistant.
However, the Pinterest tag isn't fired and I can't seem to find any exemple of React app with a Pinterest tag.
Because the previous method didn't work, I then tried the manual implementation but I don't think this this is the right code.
Manual implementation in _document.js :
<script
dangerouslySetInnerHTML={{ __html:`
!function(e){if(!window.pintrk){window.pintrk = function () {
window.pintrk.queue.push(Array.prototype.slice.call(arguments))};var
n=window.pintrk;n.queue=[],n.version="3.0";var
t=document.createElement("script");t.async=!0,t.src=e;var
r=document.getElementsByTagName("script")[0];
r.parentNode.insertBefore(t,r)}}("https://s.pinimg.com/ct/core.js");
pintrk('load', '<PINT_CODE>', {em: '<user_email_address>'});
pintrk('page');
` }}
/>
This is the solution I found:
<script
dangerouslySetInnerHTML={{ __html:`
!function(e){if(!window.pintrk){window.pintrk = function () {
window.pintrk.queue.push(Array.prototype.slice.call(arguments))};var
n=window.pintrk;n.queue=[],n.version="3.0";var
t=document.createElement("script");t.async=!0,t.src=e;var
r=document.getElementsByTagName("script")[0];
r.parentNode.insertBefore(t,r)}}("https://s.pinimg.com/ct/core.js");
pintrk('load', 'YOUR_CODE', {em: '<user_email_address>'});
pintrk('page');
` }}
/>

Why doesn't React provide a transpiler?

I'm learning about implementing React projects without create-react-app.
In every example I've studied, Babel is used to transpile JSX into JavaScript.
It seems strange to me that the React team would rely entirely on a third-party tool for their framework to function. (I am aware one can utilize the React library by writing "vanilla" JavaScript code, but that is not the common practice.)
There had to be a way to transpile React prior to the React team relying on Babel
Is there no other way to transpile JSX into JavaScript?
Why doesn’t the React team provide a tool to transpile JSX into JavaScript?
I will try to answer both questions. Since I write various code generators, I think my reasoning will be useful.
Why doesn't React provide a transpiler?
I believe that the main reason for this is not even so much that JXS appeared earlier. The main problem with the code now is its standards, which are still not fully supported by browsers. Thus, Babel is needed primarily for interpreting JS and only then JSX. And since he is so needed, why not delegate this responsibility to it.
Is there no other way to transpile JSX into JavaScript?
On the one hand - no, but not all that bad. I think the React team could quickly write their own transpiler. I say this because although there are some difficulties, they are so insignificant that it is not possible or too hard. Of course, these words can be perceived as unsubstantiated, so I chose a middle ground between writing a transpiler here and giving an example of code.
Of course, code transpilation is usually done at the development stage and not at runtime, but I will give exactly the transpilation runtime in the snippet. This is similar to when you wrap your JSX code in a script tag with type="text/babel",
and for this also includes the babel file
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
In order to get rid of goal, you can make another type of script and throw out babel.
Here is an example that I will try to create and I came up with a new type of script "text/react" and everything so that it does not start ahead of time with errors:
<script type="text/react">
const App = () => {
const clickHanler = ()=> {
alert("you clicked me")
}
return (
<button onClick={clickHanler} style={{color:'green'}}>Click me</button>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
</script>
Now you need to go through a few steps.
1 Find this script on the page.
2 Transpile it.
3 Run for execution.
To do this, in another script, I will place several functions, very simplified.
window.addEventListener('DOMContentLoaded', function () {
return transformScriptTags();
}, false);
We need to catch the moment when we can start transpiling by running transformScriptTags.
function disableScriptTags() {
window.removeEventListener('DOMContentLoaded', transformScriptTags);
}
We will eventually disable this handler.
The transpiler function will contain:
1 The way to extract tags, in fact, I used recursion for this, but the given code will be without it.
2 Next, we transform the result into an object tree with the structure:
{
tagName : ''
children : [
...
],
attributes : {}
}
3 Then we recursively put everything together in also tree like this:
React.createElement(
'h1',
{className: 'greeting'},
'Hello world'
);
4 We replace in the old script and insert it as a new one.
That's all, here's an example:
function transformScriptTags(scriptTags) {
//https://stackoverflow.com/questions/68607607/why-my-state-is-not-re-rendering-when-my-state-changes-in-this-reducer-in-redux
const code = document.querySelector('#code');
const oldScript = document.querySelector('script[type="text/react"]');
const reTag = /<(?:([A-Za-z0-9]*) ([^>]*)>(.*?)<\/\1>|[A-Za-z0-9]* [^>]*\/>)/;
const unwrap = e => e.match(/^\{.*\}$/) ? e.slice(1, -1) : e;
const wrapText = e => e.match(/^\{.*\}$/) ? e : `'${e}'`;
const ObjectToReact = (json) =>{
const result = ''
const {tagName, attributes, children} = json;
return `React.createElement(
'${tagName}'${!attributes || Object.entries(attributes).length === 0
? ', null'
: `, {${Object.entries(attributes).reduce((acc,[key, value]) => acc += `${key}:${unwrap(value)},`, '')}}`}
${children ? children.map(e => e.match(reTag) ? `,${ObjectToReact(e)}`: `,${wrapText(e)}` ) :''})`
}
const allScriptText = oldScript.innerHTML
const matched = allScriptText.match(reTag)
const element = {
tagName : matched[1],
children : [matched[3]],
attributes : matched[2].split(' ')
.reduce((acc,e) => ({...acc, [e.split('=')[0]]:e.split('=')[1]}), {})
}
const reactElement = ObjectToReact(element)
const newScriptText = allScriptText
.replace(matched[0], reactElement)
.replace('<App />', 'App()')
const newScript = document.createElement('script');
newScript.innerHTML = newScriptText;
disableScriptTags();
document.body.removeChild(oldScript);
document.body.appendChild(newScript);
code.textContent=newScriptText;
}
function disableScriptTags() {
window.removeEventListener('DOMContentLoaded', transformScriptTags);
}
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin ></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin ></script>
<div id="root"></div>
<pre id="code"></pre>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function () {
return transformScriptTags();
}, false);
</script>
<script type="text/react">
const App = () => {
const clickHanler = ()=> {
alert("you clicked me")
}
return (
<button onClick={clickHanler} style={{color:'green'}}>Click me</button>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
</script>
The underlying reason is fairly simple, JSX predates React. JSX was made public along with React, but originally it was used (in a slightly different form) inside Facebook before React ever came along.
As to why the JSX team chose to use Babel, while this is subjective speculation, building a good transpiler is really hard, and at that time Babel was already very common. Adding new functionality by integrating with Babel is considerably less work than building a transpiler from scratch. Likewise, it's less effort for the library consumers: adding a new plugin to your existing setup is easier than integrating with a whole separate toolchain.
From the planning perspective, Facebook has contributed both to Babel's finances and the project itself considerably, reducing worries that the project might simply disappear from underneath them.

How to create a redistributable widget using React

I want to build a widget using React that can be consumed by non-spa sites by pointing to a js file and adding a javascript snippet. E.g.
<script src="somepath/mycomponent.min.js"></script>
<script>MyComponent.render('id-of-a-div')</script>
I have created a component with React and setup webpack. I most spa-cases the top-level component ends with
ReactDOM.render(<MyComponent/>, document.getElementById(id));
My component won't be able to do this since it doesn't know to which element to render itself.
How and where should I create the function that would attach the component to an element?
you need a file with the methods that initialize and interacts with the parent page.
Maybe in utilities.js
export const utilities = {
// Here you will initialize the widget and you could pass an argument
// with the id of the tag where you wanna inject the app
initWidget: ( elementId ) => {
if( !elementId ){
document.createElement( 'rootApp' );
ReactDOM.render(<MyComponent/>, document.getElementById('rootApp'));
}
else {
ReactDOM.render(<MyComponent/>, document.getElementById(id));
}
},
}
And the utility will work in the tag of html to initilize it right there after all the js is loaded:
<script type='text/javascript' src='/widget.js'></script>
<script>
utilities.initWidget( 'myCustomId' );
</script>
Maybe a flow like this could be useful to you.

Issue in integrating GoogleMaps in React App

I am trying to integrate googlemaps in my React App.But it returns the following error in javascript console.
The javascript console returns the following error while trying to integrate Google Maps.How can I resolve that issue?
[Violation] Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive.
js?key=APIKEY:99
[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.
util.js:40
[Violation] Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking event handler as 'passive' to make the page more responsive.
util.js:40
[Violation] Added non-passive event listener to a scroll-blocking 'touchmove' event. Consider marking event handler as 'passive' to make the page more responsive.
How can I display Google Maps in my browsers?
I have a working solution with a different package.
However, there are a few issues with your code example, so please see if you can utilise these suggestions for resolving several issues with it.
1. Google maps script in head section
Unlike stylesheets and fonts, scripts should be loaded at the end of the body, for peformance reasons, as they will otherwise be loaded before the content, prolonging the page load.
Also, don't forget to include page title and other things, that usually help you with SEO, which are missing in your example.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style/style.css">
<link rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/48938155eb24b4ccdde09426066869504c6dab3c/dist/css/bootstrap.min.css">
<title>page title</title>
</head>
<body>
<div class="container"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY" type="text/javascript"></script>
<script src="./bundle.js"></script>
</body>
</html>
2. Map itself & User details
I've previously successfully used another package called 'react-google-maps' that seems to be working properly at this moment, so I'll add an example with that one inside the UserDetail example
Considering that you only have a render method for UserDetails, I would suggest that you use a pure functional component here.
Also, there are a few things you can do here to help with code brevity, and a few thing you should ask yourself.
why userdetail is not camelCase?
why are you passing actions to connect method, when you aren't using it anywhere inside and when it can be used directly in the render?
Are you sure you really need to import everything from actions?
import { actionName } from '../actions'
Maybe something like this would be more beneficial if you are going to use something specific.
On another note, actions aren't used anywhere here, so I've removed them from my example.
why is google maps file named google_maps? Snake case should be only used for constants, for example in the case of google maps api key that will not change:
const GOOGLE_MAPS_API_KEY
Example:
import React from 'react';
import { connect } from 'react-redux';
import GoogleMap from 'google-map-react'
const UserDetail = (props) => {
const { latitude, longitude, email, address, countryCode } = props.userDetail;
const googleMapProps = {
bootstrapURLKeys: { key: "yourKey" },
center: [parseFloat(latitude), parseFloat(longitude)],
zoom: 12
};
const noDetails = <div>no data</div>;
const hasDetails = (
<div>
<GoogleMap {...googleMapProps}></GoogleMap>
<p>Email: {email}</p>
<p>Address: {address}</p>
<p>Latitude: {latitude}</p>
<p>Longitude: {longitude}</p>
<p>Country Code: {countryCode}</p>
</div>
);
return props.userDetail
? hasDetails
: noDetails;
}
function mapStateToProps(state){
const { userDetail } = state.auth;
return { userDetail };
}
export default connect(mapStateToProps)(UserDetail);

Resources