Using CDN in React - reactjs

I've installed React via NPM and I'm having difficulty using CDN. I included the CDN scripts in the ./public/index.html file but when I use it in any component, it doesn't recognize the third-party package that I'm trying to use.
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
Tried to use Axios but it doesn't work:
axios.post("https://burger-builder-c5a0d.firebaseio.com/orders.json", order)
.then(response=>{
alert("You ordered successfully!"); //shows an alert indicating a successful process
console.log(response); //sends results to the server
this.setState({
showModal: false, //closes the modal
loading:false,
purchasable: false
})
}).catch(error=>{
this.setState({
showModal: false,
purchasable: false,
loading: false
})
console.log(error);
})
Tried to use redux and it's also not being recognized
const reduxStore= redux.createStore;
const store = createStore();
Here's the error that I'm getting

Did you import the axios or redux package via require?
Like this:
const axios = require('axios');
EDIT
You're right. You don't even need to require something since you're importing from the CDN
I tried with the HTML boilerplate from the React.js documentation and imported the CDN from your source.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function fetch() {
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then(response => console.log(response.data));
}
ReactDOM.render(<h1>{fetch()}</h1>, document.getElementById("root"));
</script>
<!--
Note: this page is a great way to try React but it's not suitable for production.
It slowly compiles JSX with Babel in the browser and uses a large development build of React.
Read this section for a production-ready setup with JSX:
https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project
In a larger project, you can use an integrated toolchain that includes JSX instead:
https://reactjs.org/docs/create-a-new-react-app.html
You can also use React without JSX, in which case you can remove Babel:
https://reactjs.org/docs/react-without-jsx.html
-->
</body>
</html>

It seems you're trying to import Redux and Axios via CDNs, although they both are available as NPM packages.
Anyways, You can simply import any CDN script by using createElement() of ReactJs.
componentDidMount = () => {
const script = document.createElement("script");
script.src = "https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js";
script.async = true;
document.body.appendChild(script);
};

Related

Can you create a React JS with cdn

Can you use React js static website only using cdn link?
Im trying to create a static website on webhosting service.
Yes, you can — in fact, that's how the Stack Snippets feature here supports React.
Here's an example that uses createElement instead of JSX (but keep reading):
const Example = () => {
return React.createElement("div", null, "Hello, React!");
};
ReactDOM.render(React.createElement(Example), document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
That's probably want you want to do. You can still write JSX code, just compile it to non-JSX code (perhaps using Babel) before you put the compiled result in your public page. Or just write code using createElement directly.
You don't have to pre-compile JSX code, but you really, really should. It's possible to compile on-the-fly in the browser, but it takes a while, causing a significant delay on page load. But for completeness, here's how you can do that using the browser-hosted "standalone" Babel library:
<!-- Your code that needs compiling goes in a type="text/babel" `script` tag -->
<script type="text/babel" data-presets="react,stage-3">
const Example = () => {
return <div>Hello, React!</div>;
};
ReactDOM.render(<Example />, document.getElementById("root"));
</script>
<div id="root"></div>
<!-- This is what supports JSX compilation (and other transformations) -->
<script src="https://unpkg.com/#babel/standalone#7.10.3/babel.min.js"></script>
<!-- These are for React -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
Notice the delay on startup.
Just for completeness, if you need to compile async/await to non-async/await for obsolete browsers, you need another script:
<!-- This example supports `async` functions in obsolete environments that don't support them natively -->
<script type="text/babel" data-presets="es2017,react,stage-3">
function delay(ms, ...args) {
return new Promise(resolve => setTimeout(resolve, ms, ...args));
}
// Example component that has a `useEffect`
const { useState, useEffect } = React;
const Example = () => {
const [message, setMessage] = useState("Hello, React!");
useEffect(() => {
// A contrived async function for demo purposes only
(async () => {
await delay(800);
setMessage("Hello again React!");
})();
}, []);
return <div>{message}</div>;
};
ReactDOM.render(<Example />, document.getElementById("root"));
</script>
<div id="root"></div>
<!-- This is the script providing runtime support for compiled `async`/`await` code -->
<script src="https://unpkg.com/regenerator-runtime#0.13.2/runtime.js"></script>
<!-- This is what supports JSX compilation (and other transformations) -->
<script src="https://unpkg.com/#babel/standalone#7.10.3/babel.min.js"></script>
<!-- These are for React -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
Notice, again, the big delay on startup.
I suggest pre-compiling the code before putting it on the page, so it's more like the first snippet above that uses createElement, which is much faster.
From what I am understanding is, you want to make a simple react app using CDN in suppose index.html
Create one HTML file
Create index.html file and add the following content. This file contains the basic HTML boiler plate code.
<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>
</body>
</html>
Include CDN links
Inside head section add
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
Create react component like this in the file
MainComponent is our react component
React component name should start with Capital letter
<script type="text/babel">
const MainContent = () => {
return (
<div>
<p>Main content goes here...</p>
</div>
);
}
//render the component to the DOM
ReactDOM.render(<MainContent />, document.getElementById('main-content'));
</script>
Open file
Open index.html file and you are done.

how to use react component in angular js

I made two apps one is for angularjs and one is to react. Now the problem is I include the react build in angularjs app and try to initialize the '' component but when I run the code it says Test is not defined.
Can someone help me with this or give me any idea how I can get out of this problem.
React Component:
import React from 'react';
import ReactDOM from 'react-dom';
class Test extends React.Component {
render() {
return (
<div>
Hello
</div>
);
}
}
angular Js Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body ng-app="angular-app">
<div id="root"></div>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
<script src="react/dist/build.js"></script>
<script>
ReactDOM.render(<Test/>, document.getElementById('root'));
</script>
</body>
</html>
You should write the following code in your react app and then load your bundle file in angularJS app.
ReactDOM.render(<Test/>, document.getElementById('root'));
Thing is, you cannot use jsx inside browser, jsx is usually transpiled using Babel into JavaScript function calls.
So 1. <Test /> will never work inside browser, you need to Babel that.
You need to expose react to you angularjs, best way I can think of is
// In react, instead of exporting component, export a function that mount component in given HTML
Export default (elm) => ReactDOM.render(<Test/>, elm)

How to have react app in the HTML without npm start or similar commands

I'm kinda new to ReactJS and don't even know if it's possible but I want my react app to be working in the browser from the .html file. without the need for calling the server and have it, working, only that way. ( I don't mind having a server to serve it obviously) just need to be able to have by calling the .html file
the public/index.html file:
<head>
<meta charset="utf-8">
<script src="/my_library/my_library.min.js"></script> <!-- needed for the project in the same folder the index.html is -->
<title>Demo</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
the index.js (in src folder):
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
React.createElement(App),
document.getElementById('root')
);
The App.jsx in the src folder
import * as React from 'react';
import './App.css';
import { MyContainer } from './components/MyContainer/index';
class App extends React.Component {
render() {
return (
<div className={ 'App' }>
<header className={ 'App-header' }>
<h1 className={ 'App-title' }>
</h1>
</header>
<MyContainer />
</div>
);
}
}
export default App;
PS: I have been able to add React to my file... But this particular component that I want to add only works with NPM Start. and as you can see in the index.html file shown above is says
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
which is exactly what I aim to change. if any one can provide some guidance or help about this, would be much appreciated.
If you just want to use React within an HTML file within a browser maybe you could just include the React library with a script tag as well as your custom React scripts with script tags as well. Their documentation has a nice example of just using React within an HTML file. I created a Codebox with their sample example for this below where the like button is using react. However, if you want to use JSX syntax you will have to use Babel, to transpile JSX into native JavaScript, and link the library like such:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
create_react_app gives you a lot of bells and whistles so you don't have to worry about setting up build configurations using tools such as webpack, babel, eslint, etc.. but this meant to give you a head start on building out an application so you can focus on the application itself and not configuration settings. Behind the scenes it's using webpack-dev-server to serve up your application, but for your use case I think it would be best to just add React as a script tag to an existing HTML page
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
Hopefully that helps!

React with Google Apps Script [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
Has anyone tried deploying a React front end to a Google Apps Script web app? I'm trying to build a single page front end that calls some of the Google Apps Script apis, like get a list of drive files and save some results to a spreadsheet. However, all the React docs seem to assume I'm using a Node.js backend and don't focus much on custom build/deploy situations. If you have seen even a simple hello world for React with Google Apps Script, would be much appreciated! Thanks.
I have zero experience with React, but their starter 'Hello, World' example from the docs is working as expected inside HTML templates. The script below is spreadsheet-bound, but the same is applicable to web apps.
Note that the attribute type="text/babel" for the <script> tag is required.
sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body id="root">
<script type="text/babel">
ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById('root'));
</script>
</body>
</html>
Result in Google Sheets sidebar:
Lot of great projects here. Also including a full-featured demo app, showing how to use React with google apps script:
https://github.com/enuchi/React-Google-Apps-Script
It uses clasp and webpack, so you can use all the new javascript you want for your .gs server-side code (such as arrow functions, const/let, etc.)
https://github.com/marth141/react-gas
Know this question was asked a long time ago but I just wrote up a thing on Google Apps Script that is React.
You can use this as like a boilerplate. Use clasp in the src folder to push and pull code to Google Apps Script
I was totally inspired by Anton's amazing idea!! So great!! To add to his idea here is an appscript with module like behaviour and a base App class and I have added redux into the mix.
Code.gs
function include(filename) {
Logger.log(filename)
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function onOpen() {
SlidesApp.getUi().createMenu('Picker')
.addItem('Start', 'showSidebar')
.addToUi();
}
function showSidebar() {
var ui = HtmlService.createTemplateFromFile('Index').evaluate().setTitle(
'Flashcards');
SlidesApp.getUi().showSidebar(ui);
}
App.js.html
<script type="text/babel">
class App extends React.Component {
constructor(){
super();
}
render() {
return (
<div>Hello World</div>
)
}
}
</script>
index.js.html - without redux
<script type="text/babel">
ReactDOM.render(<App />, document.getElementById('root'));
</script>
index.js.html - with redux
<script type="text/babel">
const Provider = ReactRedux.Provider
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
</script>
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
// Libraries for adding redux
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.7/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<?!= include('App.js'); ?>
// pull in redux if and when needed
<?!= include('redux.js'); ?>
<?!= include('index.js'); ?>
</body>
</html>
redux.js.html
<script type="text/babel">
const initialState = {
result: 1,
lastValues: []
}
const reducer = (state = initialState, action) => {
switch (action.type){
case "ADD":
state = {
...state,
result : state.result + action.payload,
lastValues: [...state.lastValues, action.payload]
}
break;
}
return state;
};
const store = Redux.createStore(reducer);
store.subscribe( () => {
console.log('Store updated!', store.getState());
})
store.dispatch({ type: "ADD", payload: 10 })
</script>

require is not defined

Im building a new React app but get the following error -
"require is not defined"
hello-world.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel" src="hello-world.js">
</body>
</html>
hello-world.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
<App />,
document.getElementById('example')
);
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
Im running this from my client and don't have any web server running.
I tried to include http://requirejs.org/docs/release/2.2.0/minified/require.js
but it gives a totally different error.
You're trying to use a CommonJS module from within your browser.
This will not work.
How are you using them?
When you write import ... from ... in ES6 Babel will transpile these calls to a module definition called CommonJS and since CommonJS isn't around in the browser you'll get an undefined error from require().
Furthermore, you're also trying to load RequireJS which uses a different module definition pattern called AMD, Asynchronous Module Definition, and will not take care of the require calls for you. You can wrap them in RequireJS specific calls.
If you want to use CommonJS modules in your code base you need to first bundle them with either Browserify or webpack. The two tools will transform your require calls to some glue magic that you can use within the browser.
But in your specific case, if you remove the import calls and just let the browser take care of and attach the classes you've created to the window object your code should work.
Also, note that when you are using submodules from React without another transpiler you will have to reference the top-level modules. I just know that in some cases there are people who will not wish refactor their projects and alter directories to handle webpack/browserify module imports.
So instead of using the CommonJS import React, {useState, useEffect} from 'react' you can instead reference hooks with React.useEffect() , React.useState().
Just another solution for those who don't want to deal with any refactoring.
Here is a basic hello world example on hooks
The code samples on react website doesn't show the full html document. In summary use React.useEffect and React.useState. Get rid of the import statement.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Example() {
const [count, setCount] = React.useState(0);
// Similar to componentDidMount and componentDidUpdate:
React.useEffect(() => { // Update the document title using the browser API
document.title = `You clicked ${count} times`; });
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);
</script>
</body>
</html>

Resources