I would like to include jquery.min.js and add a external JavaScript file and call a JavaScript function inside an existing react JS file.
I did below but it is not working
const VoCaaSComponentbtn = (
<React.Fragment>
<div>
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<script type="text/javascript"src="https:xxx/microsurvey" defer="defer"></script>
<div id="microsurvey" module="true" tab-info="tabname"></div>
<script type="text/javascript"> voc_getsurvey(); </script>
</div>
</React.Fragment>
);
You can import all the scripts in the main HTML file.
If you want to import the script inside the react component, you can use the following options.
Option 1: Use plain Javascript and React custom hook
Create custom hook [useScript.js]
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
};
export default useScript;
Use
import useScript from 'hooks/useScript';
const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}
Option 2: Use plain Javascript in ComponentDidMount
componentDidMount () {
const script = document.createElement("script");
script.src = url;
script.async = true;
document.body.appendChild(script);
}
Option 3: Use dangerouslySetInnerHTML
const codeStr = `
<div>
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<script type="text/javascript"src="https:xxx/microsurvey" defer="defer"></script>
<div id="microsurvey" module="true" tab-info="tabname"></div>
<script type="text/javascript"> voc_getsurvey(); </script>
</div>
`
<div dangerouslySetInnerHTML={{ __html: codeStr }} />
You can add External JS library in indeex.html page inside public directory.
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
One another way to add external JavaScript file. If you only want to add for specific page or component.
componentDidMount() {
var script = document.createElement('script')
script.src = // path of external javascript file.
script.class = "external-script"
document.body.appendChild(script);
}
Related
i'm roking in a ASP.NET CORE MVC project and i have a React class that is a component used in a razor page.
I tried in every single way that i found in the web but seems like console.log don't show anything.
The component is render on the page and shows the properties correctly:
and this is the inspector:
class App extends React.Component{
componentDidMount() {
console.log('hi')
}
render() {
console.log(this.props)
const { Property1, Property2 } = this.props
const handler = (event) => {
console.log(event);
}
return (
<div>
<button onClick={handler}> clicca </button>
{console.log(this.props)}
<p>Property1: {Property1}</p>
<p>Property2: {Property2}</p>
<div className="box">Sono un box</div>
</div>
);
}
}
Non of them works and i don't understand why
Index.cshtml (just a simple page with the component)
#Html.React("App",new { Property1 = "value1", Property2 = "value2" })
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
Program.cs:
//configure the services for application
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvc().AddRazorRuntimeCompilation();
//builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddReact();
builder.Services.AddHttpContextAccessor();
builder.Services.AddJsEngineSwitcher(option => option.DefaultEngineName = V8JsEngine.EngineName).AddV8();
var app = builder.Build();
// configure middleware
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseReact(config => {
config.AddScript("~/js/App.jsx");
});
ReactSiteConfiguration.Configuration.JsonSerializerSettings.ContractResolver = new DefaultContractResolver();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
}
[EDIT]
with ReactInitJavascript at the end of the Index.cshtml when i start the page, data are showen like the component was loaded correcty, but in the inspectore says that component App is not defined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title> - SportData</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/css/site.css?v=_5WottCwlLwmnX08KuvZv3ryqfP5c42il12e6LRxHqg" />
<link rel="stylesheet" href="/css/card.css?v=ZXutknPLolnM8AJ6Dofwp6kVw_54LAeyyWSi8YLbEeY" />
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
<div id="react_0HMO2J0AM8AAV"><div data-reactroot=""><button> clicca </button><p>Property1: <!-- -->value1</p><p>Property2: <!-- -->value2</p><div class="box">Sono un box</div></div></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script>ReactDOM.hydrate(React.createElement(App, {"Property1":"value1","Property2":"value2"}), document.getElementById("react_0HMO2J0AM8AAV"));
</script> --> this is the error line
</main>
</div>
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<!-- Visual Studio Browser Link -->
<script type="text/javascript" src="/_vs/browserLink" async="async" id="__browserLink_initializationData" data-requestId="6501a3e3c110465981ca8b97a81c1842" data-requestMappingFromServer="false" data-connectUrl="http://localhost:57481/dc7f1eca94044a1ca53edfa6de85d80f/browserLink"></script>
<!-- End Browser Link -->
<script src="/_framework/aspnetcore-browser-refresh.js"></script></body>
</html>
I'm trying to set up react project without CRA
Before, I've succeed reactApp with CDN.
So this time, I just want to set up reactApp with npm.
I installed react, react-dom by npm.
and index.html below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.js"></script>
</body>
</html>
index.js below
import React from "/react";
import { ReactDOM } from "react-dom";
const createEle = React.createElement;
const domContainer = document.querySelector("#root");
const root = ReactDOM.createRoot(domContainer);
root.render(createEle(LikeButton));
function LikeButton() {
const [liked, setLike] = React.useState(false); //
if (liked) {
domContainer.style.backgroundColor = "red";
return createEle("button", { onClick: () => setLike(false) }, "Hate");
} else {
domContainer.style.backgroundColor = "green";
return createEle("button", { onClick: () => setLike(true) }, "Like");
}
}
I don't want to use webpack, babel.
but after I open the index.html, it doesn't work. Only after setting webpack, it works.
So how webpack makes reactApp alive?
Many people say that to Set up reactApp without CRA , it needs webpack because it bundles complicated so many files .
But In my case , I simplify the App and I just want to run it.
I want to know the webpack's role in my case. (the purpose i need webpack in this case
Webpack inject react and reactdom source
To use it without webpack or other module bundler you need to add react source
React cdn for development
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
React cdn for production
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
// Import is commented because script is not used as module in stack snippet. you can uncomment this.
//import React from "/react";
//import {
// ReactDOM
//} from "react-dom";
const createEle = React.createElement;
const domContainer = document.querySelector("#root");
const root = ReactDOM.createRoot(domContainer);
root.render(createEle(LikeButton));
function LikeButton() {
const [liked, setLike] = React.useState(false); //
if (liked) {
domContainer.style.backgroundColor = "red";
return createEle("button", {
onClick: () => setLike(false)
}, "Hate");
} else {
domContainer.style.backgroundColor = "green";
return createEle("button", {
onClick: () => setLike(true)
}, "Like");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<script type="module" src="./src/index.js"></script>
</body>
</html>
My component looks like this:
import React from "react"
function about(props) {
return (
<>
<h2>List users:</h2>
<ul>
{props.users.map((user) => {
return <li>{user.name}</li>
})}
</ul>
</>
)
}
export default about
export async function getStaticProps() {
console.log("Pedido GSP")
const res = await fetch("https://jsonplaceholder.typicode.com/users")
const users = await res.json()
return {
props: {
users,
}, // will be passed to the page component as props
revalidate: 60
}
}
My generated HTML file after build looks like these:
<!DOCTYPE html>
<html>
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width"/>
<meta name="next-head-count" content="2"/>
<link rel="preload" href="/_next/static/css/120f2e2270820d49a21f.css" as="style"/>
<link rel="stylesheet" href="/_next/static/css/120f2e2270820d49a21f.css" data-n-g=""/>
<noscript data-n-css=""></noscript>
<script defer="" nomodule="" src="/_next/static/chunks/polyfills-a40ef1678bae11e696dba45124eadd70.js"></script>
<script src="/_next/static/chunks/webpack-93d688579f639ac646b4.js" defer=""></script>
<script src="/_next/static/chunks/framework-fb2dd7aba3784ca05084.js" defer=""></script>
<script src="/_next/static/chunks/main-89e612c37cd79392e22d.js" defer=""></script>
<script src="/_next/static/chunks/pages/_app-fd5464216d5252770dc3.js" defer=""></script>
<script src="/_next/static/chunks/pages/GSSP-43e12c3600ead54767ee.js" defer=""></script>
<script src="/_next/static/zNXWEGrv_m38JDMSXfB2l/_buildManifest.js" defer=""></script>
<script src="/_next/static/zNXWEGrv_m38JDMSXfB2l/_ssgManifest.js" defer=""></script>
</head>
<body>
<div id="__next"></div>
<script id="__NEXT_DATA__" type="application/json">
{"props":{"pageProps":{"users":[{"id":1,"name":"Leanne Graham","username":"Bret","email":"Sincere#april.biz","address":{"street":"Kulas Light","suite":"Apt. 556","city":"Gwenborough","zipcode":"92998-3874","geo":{"lat":"-37.3159","lng":"81.1496"}},(...),"page":"/GSSP","query":{},"buildId":"zNXWEGrv_m38JDMSXfB2l","isFallback":false,"gssp":true,"scriptLoader":[]}
</script>
</body>
</html>
For what I've been learning the <div id="__next"></div> should'nt be empty, it should contain the list of users already rendered.
The page loads normally, but I believe the list is being created on the browser instead of being on the server. I'm new to Next and I got to this result while merging the project with Redux.
Also why are so many <script> tags being generated at the begining?
Thanks in advance.
Well I got it working and came here to help others that might have the same problem.
If you're using Redux with redux-persist, the PersistGate is causing the issue. Pass the store with a Provider and the issue is gone (the store will still persist).
I've tried to put <script src="https://www.wiris.net/demo/plugins/app/WIRISplugins.js?viewer=image"></script> in the <head> of my index.html using reactjs, however, for some reason this didn't work for me.
client/public/index.html
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Portal</title>
<!-- WIRISplugin -->
<script src="https://www.wiris.net/demo/plugins/app/WIRISplugins.js?viewer=image"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
When I run the app the math equation remains not displaying and I received on console the 404 error, as the script wasn't able to access the Wiris URL and get the plugin.
Current results:
a3xy=∞∅π
21,4 mol ⇄ a∆N
Expected results:
Could someone help me? I've read the documentation on the Wiris website (https://docs.wiris.com/en/mathtype/mathtype_web/integrations/mathml-mode), but I wasn't able to identify why this didn't work.
Add the below script to your index.html or the page where you want to render mathml
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
Create a new component which will be used to render your math equations
function Latex(props) {
const node = React.createRef();
const renderMath = () => {
window.MathJax.Hub.Queue(['Typeset', window.MathJax.Hub, node.current]);
};
useEffect(() => {
renderMath();
});
return (
<div ref={node} {...props}>
{props.children}
</div>
);
}
Wrap your content with <Latex /> component and it will render your equations
could anyone help me out here? Just trying to embed a simple Skype button in my react app, but due to my apparent lack of understanding of modules, imports, webpack, and how create-react-app actually does what it does, I can't access the Skype object. It's not defined.
I have followed instructions
https://www.skype.com/en/developer/create-contactme-buttons/
I have linked to the skype js using a script tag in my index.html's <script type="text/javascript" src="https://secure.skypeassets.com/i/scom/js/skype-uri.js"></script>
inside my main js file, using create-react-app:
loadSkype() {
Skype.ui({
"name": "dropdown",
"element": "SkypeButton_Call_john23",
"participants": ["john23"],
"imageSize": 32
})
}
I can not access the Skype object. Any ideas?
The instructions make it sound really simple: copy and paste the following code:
<script type="text/javascript" src="https://secure.skypeassets.com/i/scom/js/skype-uri.js"></script>
<div id="SkypeButton_Call_john23_1">
<script type="text/javascript">
Skype.ui({
"name": "call",
"element": "SkypeButton_Call_john23_1",
"participants": ["john23"]
});
</script>
</div>
On your index.html you need import the skype library:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="https://secure.skypeassets.com/i/scom/js/skype-uri.js"></script>
</body>
</html>
Then create a component for skype and import it whenever you want to use it:
import React from "react";
import { render } from "react-dom";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
class SkypeBT extends React.Component {
componentDidMount() {
Skype.ui({
name: "dropdown",
element: "SkypeButton_Call_john23",
participants: ["john23"],
imageSize: 32
});
}
render() {
return <div id="SkypeButton_Call_john23" />;
}
}
const App = () => (
<div style={styles}>
<h2>Call me</h2>
<SkypeBT />
</div>
);
render(<App />, document.getElementById("root"));
You can fid a working version in here
This snippet creates a button for your website, if you need to create an object then you should create a new div element and set the id to SkypeButton_Call_john23_1. Then you need to create a script element and place the json inside it.
loadSkype() {
var div = document.createElement('div');
div.id = 'SkypeButton_Call_john23_1';
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.value =
Skype.ui({
"name": "call",
"element": "SkypeButton_Call_john23_1",
"participants": ["john23"]
});
div.appendChild(s);
return div;
}