Can you create a React JS with cdn - reactjs

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.

Related

Next.js getStaticProps() not rendering static HTML properly

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).

How to use JSX properly for react, i'm getting an error

I'm new in ReactJs n my first code test. The tuto says that this will work:
HTML(index.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>react test</title>
</head>
<body>
<div id="root"></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 code -->
<script src="pba.js"></script>
</body>
</html>
JS(pba.js):
const element = {<h1>Hello, world!</h1>};
ReactDOM.render(
element,
document.getElementById('root')
);
Problem:
pba.js:3 Uncaught SyntaxError: Unexpected token '<'
You should use a build tool like
create react-app, gatsby or next.js
What you are doing here is loading a javascript file directly into an html document.
However the Javascript file has no idea, what React is. If you don't want to use an independent build tool like suggested above, you can use webpack to bundle your code.
Here is a tutorial on how to do this: https://www.valentinog.com/blog/babel/
otherwise look into create react app:
https://www.google.com/search?q=create+react+app&oq=create+react+app&aqs=chrome..69i57j0l7.3442j1j7&sourceid=chrome&ie=UTF-8
Your element component needs to be a function or a class component. Note that doing the following will also work, but using one component as a root component for your app is better than just rendering one element.
const greeting = 'Hello World';
const element = <h1>{greeting}</h1>;
// or const Element = [<h1>{greeting}</h1>, <h1>Hello again</h1>];
ReactDOM.render(element, document.getElementById('root'));
Using function/class component
// pba.js
const Element = () => (<h1>Hello World</h1>)
ReactDOM.render(<Element />, document.getElementById('root'));
and also you need to add babel cdn to transpile your react code, add type text/babel to your script tag. <script type="text/babel" src="pba.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>react test</title>
</head>
<body>
<div id="root"></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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<!-- Load our React code -->
<script type="text/babel" src="pba.js"></script>
</body>
</html>
Just change your pba.js file as follows:
const element = React.createElement("h1", {}, "Hello, world!");
ReactDOM.render(element, document.getElementById("root"));
While this is possible, there are a couple of things wrong with your code.
It looks like goto1 is correct, you can just use the () syntax for this, but you need to use () instead of {}
While goto1 is correct, the first argument in ReactDOM.render(...) does not have to be a function or class (just valid JSX), I am 110% recommending you stick to using functions or classes...
You need to use something like Babel Standalone so your React code can be translated into something a browser will understand
I have made a lot of comments with examples in the demo below, which should help you out.
Demo:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>react test</title>
</head>
<body>
<div id="root"></div>
<div id="root-two"></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 Babel Standalone -->
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<!-- Load our React code -->
<!-- Notice the 'type="text/babel"' attribute -->
<script type="text/babel">
// This was done for the sake of simplicity, you can still load your .js file here
// While goto1 is technically correct, I recommend sticking
// to using functions or classes..
const Element = () => {
return ( <h1>Hello, world!</h1> );
}
// This means you can do things like:
// Notice our component from above, Element, is reusable here..
const AnotherElement = () => {
return (
<div style={{textAlign: 'center', color: 'blue'}}>
<Element />
</div>
);
}
// Keep in mind using `()` syntax versus a function or class, means this is not reusable at all..
// The following is NOT reusable!
// const element = ( <h1>Hello, world!</h1> );
// You could also drop the `()` as it is used to group lines of code,
// something like this is also not reusable (but would still work in
// this scenario)!
// const element = <h1>Hello, world!</h1>
// For example, this wouldnt work
// const anotherElement = ( <element /> );
// This would also not work
// class SomeClass extends React.Component {
// render() { return ( <div><element /></div> ) }
// }
// This would not work either
// const SomeComponent = () => {
// return ( <div><element /></div> );
// }
ReactDOM.render(
// goto1 is correct, it looks like you can use an object as you were.
// Please be mindful of this as it is not reusable!
// I recommend sticking to either functions or classes, until you are more comfortable with React
<Element />,
document.getElementById('root')
);
// For the second example, demonstrating how using functions or classes
// is reusable, whereas your original example was not:
ReactDOM.render(
<AnotherElement />,
document.getElementById('root-two')
);
</script>
</body>
</html>

add react to a website : how import external node module?

from this ressource https://reactjs.org/docs/add-react-to-a-website.html I have integrate into my static website a basic component
<body>
<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>
<script src="https://unpkg.com/react-content-loader#3.4.1/dist/react-content-loader.min.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
like_button.js :
'use strict';
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return (
<div>
<button onClick={() => this.setState({ liked: true }) }>
Like
</button>
<Facebook /> ???????????
</div>
);
}
}
let domContainer = document.querySelector('#like_button_container');
ReactDOM.render(<LikeButton />, domContainer);
How to use in this component an external module like https://www.npmjs.com/package/react-content-loader ?
I tried to add script https://unpkg.com/react-content-loader#3.4.1/dist/react-content-loader.min.js into html page with import satement in my component but I have an error "Uncaught ReferenceError: Facebook is not defined"
I never tried the code in Add React to a Website chapter of the React documentation. It was a good time to tinker with it.
There are more than one potential problem with your attached code. You do not load Babel in your index.html. At least in the question. So you could not use jsx syntax in the like_button.js.
The second one is that you could not use import here. You have to find what is the namespace of the package. I logged out the window object, checked that and it is ContentLoader.
The rest is easy I created a standalone index.html with babel:
https://codesandbox.io/s/w27pjmq355
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hello React!</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>
<script
src="https://unpkg.com/react-content-loader#3.4.1/dist/react-content-loader.min.js"
crossorigin
></script>
<script src="https://unpkg.com/babel-standalone#6.26.0/babel.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
console.log('window', window);
class App extends React.Component {
render() {
return (
<div>
<h1>Hello world!</h1>
<ContentLoader.Facebook />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>
I think you could try out React this way, but Babel usage is not recommended like this in production. I strongly recommend to install node and use create-react-app. This way you can use the whole toolchain in no time.
Or event create a new React sandbox on CodeSandbox.io

Simple JSX throws error in console

React noob here, I am working on a simple JSX based component with the code below:
<!DOCTYPE html>
<html>
<head>
<title>React Boot camp Day 1</title>
</head>
<body>
<div id='app'></div>
<!--Needed for react code-->
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<!--Needed for react dom traversal-->
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src='https://unpkg.com/babel-standalone#6/babel.min.js'></script>
<script>
console.log('Test React', window.React)
const name = "Callat"
const handle = "#latimeks"
// create components and use jsx
function FirstComponent(props){
return <h1>{props.name}</h1>
}
function TestJSX(){
return (<FirstComponent name={name}/>)
}
ReactDOM.render(<TestJSX/>, document.getElementById('app'))
</script>
</body>
</html>
Running this code yields no UI and in dev tools I see this
Uncaught SyntaxError: Unexpected token < index.html:42
Which is the
function FirstComponent(props){
return <h1>{props.name}</h1>
}
What is wrong here? According to everything I've seen online and in the bootcamp instructions my syntax is correct and this should work.
Can anyone give some insight?
I found an answer to this. Including the CDN was only part of the fix. The second part is to include the following:
<script type="text/babel">//My react code</script>
Once that's done reloading the page works. I really should get more used to the native react ecosystem though.

Cannot get basic React with JSX example to work

Any pointers would be appreciated. I'm new to React and JSX and Babel and am just trying to get something bare-bones working. I've been at this for a while and I'm at a dead end.
Here's my html page:
<!DOCTYPE html>
<html>
<head>
<title>Test React</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script type="text/babel" src="../TestReact/res/js/main.jsx"></script>
</head>
<body>
<div>Page to Test React Library</div>
<p></p>
<div>
<button onclick="addComponent()">Add Component</button>
</div>
<p></p>
<div id="root">
</div>
</body>
</html>
And here's my "main.jsx" file:
addComponent = function (){
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
};
I'm using Chrome 61.
If I include either type="text/babel" or type="text/jsx" on my script tag, I get an exception: "Uncaught ReferenceError: addComponent is not defined".
If I remove this type attribute on the script tag, then (of course) I get an error for "unexpected token <" because the html/xml is not going to be transpiled.
When I have the type attribute (for jsx/babel) on the script tag removed AND I enclose the html in my addComponent method in quotes, then I get no errors, but I end up with the literal string
"<h1>Hello, world!</h1>"
rendered on the page in the 'root' div instead of an embedded header element - naturally, but at least that tells me that my small javascript and ReactDOM library are imported and working.
So it seems like the problem is that the JSX transpiling is not happening for some reason.
<---- UPDATE 201710011830 ---->
It seems that the problem I'm having is related to having ReactDOM.render called from within a javascript function ("addComponent") in my JSX file that is supposed to handle a button onclick event. If I remove the addComponent function so that main.jsx looks like this:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
then the h1 element is inserted on the page as it should be.
So the question then becomes, why won't it work the way I initially intended? Is it because of the syntax I used to define that addComponent function within the original JSX script?
You need to add bundle.js to your index.html file like below.
<body>
....
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
bundle.js is the distribution which packs all the react components and dependencies and put them together in your dev environment using webpack.
Add type="text/babel" to your script tag will transform your code which in main.jsx file. I think this transform effect your addComponent function that makes your code doesn't work.
You can try just put the jsx or react component code in main.jsx, like: window.Hello = <h1>hello</h1>; then in the html(or somewhere out of main.jsx), you can write
addComponent = function (){
const Hello = window.Hello;
ReactDOM.render(
<Hello />,
document.getElementById('root')
);
};
But I highly recommend use webpack, a simple demo: https://github.com/yujiangshui/react-i18n-demo

Resources