Now that we know what React JS is, we can start with different usage of ReactJS. If you don’t know what React JS is, read the Getting Started with ReactJS.
In this article, we will learn to use React JS directly in the HTML file. There are some prerequisites to adding React JS script inside the HTML code. We need to include the following three javascript in the head section of the HTML file.
- React DOM
- React JS
- Babel Js
The first two allow us to write ReactJS code in our JavaScripts, and Babel Js will allow to write JSX syntax and ES6 in older browsers.
Follow the below steps to add react JS compnent to the HTML file.
Add the DOM container to mount ReactJS Component
Embedding React JS in HTML differs slightly from what we have done with React Js App. In a standard React Js app, the root element in the index.html is the container that mounts the React Js app. Similarly, we need any element to mount our react JS component in HTML file as below,
<div id="example"></div>
In above code, we have added an element with id example
in HTML file.
Add required JS files to run ReactJS
We want to run a React app in an HTML file, where no node_modules
to provide React Js dependencies. Therefore, we must add React dependencies by including React script tags in the HTML document as below,
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
In above code, we have included the required React JS scripts, which are required to execute the React JS code.
React Js code returns JSX. So, we also need Babel JS to transform that JSX as below,
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
Write ReactJS code in HTML
Now, our HTML file is ready for react JS code. But, we have to add our react JS code in text/babel script tag as babel can transpile our react JS code as below,
<script type="text/babel">
function Hello() {
return <h1>Hello World!</h1>;
}
ReactDOM.render(<Hello />, document.getElementById('example'))
</script>
Example
The complete code of using React JS in the HTML file is as follows,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
function Hello() {
return <h1>Hello World!</h1>;
}
ReactDOM.render(<Hello />, document.getElementById('example'))
</script>
</body>
</html>
This way, we can use ReactJS for testing purposes. But for production use, we have to set up a React environment.