Question about ReactDOM.createRoot(document.getElementById('root')).render(<App />) - reactjs

I am following the course of Full stack. https://fullstackopen.com/en/part1/introduction_to_react
It uses npx create-react-app part1 to create a example react project.
So for this statement in index.js
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
the course says that document.getElementById('root')) is using the content defined in the file public/index.html, having the id value 'root'.
So I wonder if we can modify something in the index.html to influence what will show in the result of web application. I tried but failed with no influence.
The corresponding part of "public/index.html, having the id value 'root'." is defined as following:
<div id="root"></div>

You can modify everything in the index.html.
Entire content of <div id="root"></div> will just be replaced with the React app.

Related

How to execute <script> tag in react JSX without modify whole script content tag?

Cant execute script tag inside react JSX.
I have a var with full script tag and code content and I cant modify it to create script as obect.
For example:
const html = <script type=\'text/javascript\'>console.log(1)</script>
So, I need execute html, ex:
render(){ return ( <div>{html}</div> )}
But it doesnt work, looks like code added after page render and DOM doesnt understand that script tag was append and execute it.
Find easy solution with react-postscribe.
<PostScribe html={'<script type="text/javascript">console.log(1)</script>'} />

How to get minified files in project ( Gatsby / React )

gatsby version = 2.0.0-beta.19
node version = v10.6.0
npm version = 6.1.0
VScode version = 1.25.1
When adding minified files (.min.js or .js with minified content) to my react Gatsby project, I get the following error when I try to do gatsby develop:
ERROR Failed to compile with 1 errors 10:41:47 AM
error in ./src/components/appinsights.js
Module Error (from ./node_modules/eslint-loader/index.js):
/mnt/d/my_site/src/components/appinsights.js
2:185 error Expected an assignment or function call and instead saw an expression no-unused-expressions
2:248 warning Unexpected use of comma operator no-sequences
2:493 warning Unexpected use of comma operator no-sequences
2:649 error Expected an assignment or function call and instead saw an expression no-unused-expressions
2:660 warning Unexpected use of comma operator no-sequences
2:761 warning Unexpected use of comma operator no-sequences
7:1 error Expected an assignment or function call and instead saw an expression no-unused-expressions
7:31 warning Unexpected use of comma operator no-sequences
✖ 8 problems (3 errors, 5 warnings)
I added a new file "./src/components/appinsights.js" and the contents of the file are from inside the script tag of App insights JS snippet
var appInsights=window.appInsights||function(a){
function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
}({
instrumentationKey: "<my_key>"
});
window.appInsights=appInsights,appInsights.queue&&0===appInsights.queue.length&&appInsights.trackPageView();
In my "./src/components/layout.js"
import appinsightsFile from './appinsights.js'
...
<Helmet
title={data.site.siteMetadata.title}>
<html lang="en" />
<script type="application/ld+json">{appinsightsFile}</script>
</Helmet>
...
I am not sure if this is a react issue or Gatsby. I can't seem to get any minified code to work with my application.
I have tried:
inline app insights code in my layout.js
taking the script tags out of the helmet code
I am not that experienced and wanted to comment on this, but I need 50 reputation. Anyways, maybe we can solve your issue together.
First off, why do you use type application/ld+json instead of text/javascript as stated in the ApplicationInsights-JS readme?
To debug this issue try to insert the contents of appinsights.js directly into the script tag.
The following should work:
<Helmet
title={data.site.siteMetadata.title}>
<html lang="en" />
<script type="text/javascript">
{`SCRIPT`}
</script>
</Helmet>
If not, try dangerouslySetInnerHTML instead.
Note the back ticks inside {}. If this is working correctly, proceed with your component.
As I know – correct me if I go wrong – the use case of directly importing a file in Gatsby belongs to static files. You could simply import logo from './Logo.svg' and this will return the url to that file. Behind the scenes, Webpack will include that file in the bundle and you can reference it like in src and href attributes.
If you want to include that JavaScript string from a component (that what you placed inside the components directory is not a component), you should write a component for that, which renders this JavaScript.
I didn't try that myself, but I think this could work with some modification.
The errors you are facing are part of eslint, I think. The compiler (Webpack?) expects non-minified ES6 JavaScript. Again, correct me if I am wrong.
Some sort of a stateless functional component should help you here:
appinsights.js
import React from 'react'
const AppInsights = () => {
return `
SCRIPT
`
}
export default AppInsights
layout.js
import AppInsights from './appinsights.js' // Replace with your path.
<Helmet
title={data.site.siteMetadata.title}>
<html lang="en" />
<script type="text/javascript"><AppInsights /></script>
</Helmet>
But I think it is safer to work with dangerouslySetInnerHTML as before.
https://www.gatsbyjs.org/docs/adding-images-fonts-files/
If you put a file into the static folder, it will not be processed by Webpack. Instead it will be copied into the public folder untouched.
You create a folder as your_gatsby_project_folder/static (not in project/src), and put your minified files from outside in it. Whatever is in the static will be copied onto public folder so you can link to them as usual
// in your react file, you can use script tag to link to the minified files
render(){
return(
<div>
<script src="/path/to/your/min.js" />
whatever
</div>
)
}
If you want to take a minified javascript file and add it to a <script tag in the <head of your Gatsby site, you do not want to import it.
Check the docs on custom html.
You could put the file into the static/ folder, then it will be copied into your built output. Then cp .cache/default-html.js src/html.js and edit src/html.js to add the <script tag you want.
However, this is not a very good approach. You would be better to give Gatsby the unminified file if you can. Then you can import it in the normal Gatsby way, and Gatsby will handle minifying it. Gatsby is really good at figuring out what javascript is required where. It's part of why Gatsby sites are so insanely fast. You will lose some of that advantage if you use the approach above.

How to place a third party script tag in the HEAD in gatsby

Gatsby sort of provides a way to manipulate the main html.js link to gatsby docs
but this is still a React component and I need to place a custom analytics script inside the Head. I tried eval, surrounding the script content in curly bracket, nothing works.
Found a workaround using dangerouslySetInnerHTML. Since it will strip our script tags I just placed a script tag in the Head and set the attr dangerouslySetInnerHTML to the content of the script provided by third party. e.g. in the render function of html.js:
const googleOptimizeFlickeringScript = {
__html: `(function(a,s,y,n,c,h,i,d,e){..........`
}
return (
<html>
<head>
<style dangerouslySetInnerHTML={googleOptimizeFlickeringStyle} />
<script dangerouslySetInnerHTML={googleOptimizeFlickeringScript}/>

script tag breaks sightly data-sly tag in author mode

I am using angular with sightly. So I have angular html template surrounded by script tag, which also has sightly attributes like data-sly-resource.
Below example code will give you clear idea.
<script type="text/ng-template" id="example.html">
<section data-sly-resource="${ #path='textOverImage', resourceType='example/components/textOverImage'}" id="textOverImage" >
<div ng-include="'private/textOverImage.html'" data-sly-test="${!wcmmode.edit}"></div>
</section>
</script>
It works fine in non-edit mode , but in edit mode, I can not author data-sly-resource part. It looks like <script> tag is not letting it work roperly because when I remove <script> tag ,than I can author it.
And removing script tag is not an option as well.
So how can I stop script tag form breaking sightly functionality in edit mode?
I ended up doing repetition of code , one for author mode and other for non edit mode.
Below is close resemblance of my solution.
<section data-sly-resource="${ #path='textOverImage', resourceType='example/components/textOverImage'}" id="textOverImage" data-sly-test="${wcmmode.edit}" >
<div ng-include="'private/textOverImage.html'"></div>
</section>
<script type="text/ng-template" id="example.html" data-sly-test="${!wcmmode.edit}">
<section data-sly-resource="${ #path='textOverImage', resourceType='example/components/textOverImage'}" id="textOverImage" >
<div ng-include="'private/textOverImage.html'"></div>
</section>
</script>
As you can see in above code, what to show and when works via data-sly-test="${wcmmode.edit}".
I also tried to to create sightly template for redundant code and than try data-sly-use but now, it works in author mode but sightly can't put template inside <script> tag even though I used # context='unsafe'
There is a workaround based on the Sightly Reference
Put the markup inside a separate html file say mymarkup.html parallel to mycomponent.html
In Component HTML file (e.g mycomponent.html) use <script type="text/ng-template" data-sly-include="mymarkup.html"></script>
In mymarkup.html we can use Sightly tags normally and those would be evaluated/executed normally, we would not even need to specify the # context for variables we would read using use API. The final markup rendered by component mycomponent.html when dragged to page would render something like this below
<script type="text/ng-template">
//mymarkup.html evaluated content here
</script>
In your script tag you could add data-sly-unwrap="${wcmmode.edit}"
This will remove script tag in edit mode allowing you to edit included components but in any other mode the script tag gets rendered.
I found the following mention in Netcentric's AEM Sightly Style Guide:
Then, because the HTML grammar ignores elements located inside a
< script > or < style > elements, no block statement can be used within
them.
Although it's not explicitly stated in the Sightly spec, it makes sense. So your fix is right.

How to use a file from Ext.example

I went through the docs to find for a Ext.example.msg but, i am unable to find it.
According to this example, they have successfully used Ext.example.msg. How is this ?
I had another question on SO which is related to this.
UPDATE
I am trying to use the following code in my application;
Ext.example.msg('Button Click', 'You clicked ta button');
When i execute the code, i get an error saying TypeError: Ext.example is undefined .
To overcome this error i did the following;
1.) added <script type="text/javascript" src="app/extjs/examples/shared/examples.js"/> in my app.html file
2.) added the following in my app.js file
Ext.Loader.setPath('Ext.example', 'app/extjs/examples/shared');
Ext.require(['Ext.container.Viewport',
'Ext.example.*']
);
None of the above methods works, i still get the same error message.
My project folder structure is as follows;
Project_Name
->app (folder)
--> app.html
--> app.js
--> extjs
---> examples
---->shared
----->example.js
When you include your js script in you index.html, as you did in 1:
<script type="text/javascript" src="app/extjs/examples/shared/examples.js"/>
You no longer need loader or to require it - you have explicitly included it and it is clear the script content will be in scope.
It appear to me your path is incorrect: There's no app/extjs and it would make sense to have the extjs folder as sibling to that of your app. Thus this should work:
<script type="text/javascript" src="extjs/examples/shared/examples.js"/>

Resources