Using ReactJS from CDN


To start working with react, we need to first install reactjs. You can easily get started to use reactjs by using the CDN javascript files, as shown below.

Go to the official site of reactjs to get the CDN links, i.e., https://reactjs.org/docs/cdn-links.html and you will get the required files to explain the following image.

For dev

<script crossorigin src="https://unpkg.com/react@version/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@version/umd/react-dom.development.js"></script>

For prod:

<script crossorigin src="https://unpkg.com/react@version/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@version/umd/react-dom.production.min.js"></script>

Replace version with the latest react version for both react-development.js and react-dom.developement.js. You can host the files at your end to start working with reactjs.

In case if you are planning to use the CDN files, make sure to keep the cross-origin attribute, to avoid cross-domain issues. Reactjs code cannot be executed directly in the browser and needs to be transpired using Babel to javascript before executing in the browser.

Here is the BabelJS script that can be used:

<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

Here is the working example using cdn files and babeljs script.

<!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>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head> <body>
<script type="text/babel">
<div id="app"></div>
<h1>Hello, from viastudy Tutorials!</h1>,
ReactDOM.render(
</script>
document.getElementById('app') ); </body>
</html>

Output:

We will get into the details of the code in the next chapter, let us see the working here with CDN files. It is said that using babel script directly is not a good practice, and newcomers can just use it to learn reactjs for now. In production, you will have to install react using npm package.

No comments:

Post a Comment