Adding React using script tags
How to Add React Using Script Tags?
To add React using script tags directly in your HTML file you can use a Content Delivery Network (CDN) to include the necessary React libraries. Here's a step-by-step guide:
Create an HTML File
-
Create an HTML file for your website if you don't already have one. You can do this with a simple text editor like Notepad or any code editor of your choice. Save the file with an
.html
extension. -
Create the basic structure of your HTML file, including the
<!DOCTYPE>
,<html>
,<head>
, and<body>
tags. Inside the<head>
section, add a title for your page.
Add Script Tags for React and ReactDOM
-
To include React and ReactDOM, add the following script tags inside the
<body>
section of your HTML file, just before the closing</body>
tag<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>
Create a Container for Your React App
-
Add a
<div>
element where your React app will be rendered. Give it an id so that you can target it in your React code<div id="root"></div>
Write Your React Code
-
Create a new JavaScript file (e.g.,
app.js
) in the same directory as your HTML file. This file will contain your React code. -
In your
app.js
file, write your React code. Here's an example of a simple React componentapp.js// Your React code goes here
const element = React.createElement("h1", null, "Hello, React!");
ReactDOM.render(element, document.getElementById("root"));
In this example, we create a React element with the text "Hello, React!" and render it inside the <div>
with the id 'root'.
Link the JavaScript File
-
In your HTML file, add a
<script>
tag to link your JavaScript file just before the closing</body>
tag:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Add React</title>
</head>
<body>
<!-- React component will get loaded inside this div. -->
<div id="root"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<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>
<!-- Load React component. -->
<script src="app.js"></script>
</body>
</html>
View Your Website
Save the HTML file and open it in your web browser. You should see your React app running.
This approach is best for small, simple React apps. For larger projects, use tools like create-react-app or Webpack for better code management and features like JSX and component organization.