1. What is React?
React is a JavaScript library for building user interfaces (UIs). It was created by Facebook. The key idea behind React is to break down a complex UI into smaller, reusable pieces called components.
Instead of modifying the website's HTML directly, React manages a "virtual" copy of the UI in memory. When data changes, React efficiently calculates the best way to update the real UI to match the virtual one. This makes applications fast and responsive.
2. The Basic HTML Setup
For this tutorial, we don't need any complex tools. We can run React directly in an HTML file. All we need is a single div element with an id="root". This div is the container where our entire React application will be rendered.
We also need to include three scripts in our file:
- React: The core React library.
- React DOM: The library that allows React to interact with the web browser's DOM (the HTML).
- Babel: A JavaScript compiler that lets us use modern features like JSX (which we'll cover in Module 2) directly in the browser.
Here is the complete boilerplate for our project:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Hello World</title>
<!-- React Libraries -->
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<!-- Babel Compiler -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<!-- This is where our React app will be mounted -->
<div id="root"></div>
<script type="text/babel">
// Our React code will go here!
</script>
</body>
</html>
type="text/babel" attribute on the script tag is essential. It tells Babel to find and compile our React code.3. Rendering "Hello, World!"
Now, let's write our first lines of React code. Our goal is to render an h1 element inside the root div.
To do this, we use the ReactDOM.createRoot() method to take control of our container div. Then, we use the root.render() method to tell React what to display inside it.
Add the following code inside your <script type="text/babel"> tag:
// 1. Select the root container element
const container = document.getElementById('root');
// 2. Create a root for the React application
const root = ReactDOM.createRoot(container);
// 3. Define the element you want to render
const element = <h1>Hello, World!</h1>;
// 4. Render the element into the root
root.render(element);
If you save this file as module1.html and open it in your browser, you will see "Hello, World!" displayed on the page. Congratulations, you've just built your first React application!