React is different from other JavaScript frameworks because it is written in JSX, a mix of JavaScript and HTML. Since JSX is not directly understood by the browser we need to convert it to basic JavaScript to run it on the browser.
So there are 2 ways you can run your react app on your browser.
Setting up a development environment - In this method node.js is used, where we use tools like create-react-app to set up the development environment and a local server. Every time you build a react app the JSX is converted to Javascript.
Convert directly in the browser using CDNs: Here we rely on Javascript Libraries to do the conversion of JSX. This does not need any installs on our PC.
We will be looking at how to do the 2nd method. The 1st method is appropriate if you are trying to build and deploy an app in real life. But it’s more complex and time-consuming.
The 2nd method is best for you if you are just starting on React or just want to quickly try out things in React without setting up a development environment.
All you need is a browser and a text editor and you are good to go.
Steps to run React directly on browser without Node.js or create-react-app.
Create the HTML file, lets call it index.html
Copy the boilerplate of HTML5 to index.html
Add these three script tags under the title tag.
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script> <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
The first two lines are to bring the core React library to do React things on your DOM.
The third line references Babel, the compiler which does the conversion of JSX to Javascript.
This would be how your index.html looks.
- Now we can start to write the React code inside the script tag.
- For Babel to work on this script, set the type attribute on the script tag to a value of text/babel.
- Now you can preview your page.
<!DOCTYPE html>
<html>
<head>
<title>React</title>
</head>
<body>
<script>
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>React</title>
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<script>
</script>
</body>
</html>
ReactDOM.render(
<h1>Hello World</h1>,
document.body
);
<script type="text/babel">
ReactDOM.render(
<h1>Hello World</h1>,
document.body
);
</script>
"Thank you for recommending Plantlane's watering can ! I purchased one and it's made such a difference in how I care for my plants."
ReplyDelete