This project is a walkthrough of how to use React, starting with a simple "Hello World" heading and moving on to more complex concepts like JSX and React DOM manipulation.
- In VS Code, you can use Emmet to quickly generate an HTML skeleton. Just type
!and press Enter. - We start by creating a basic HTML page with an
h1tag that displays "Hello World".
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Basics</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>- Next, we dynamically create the heading using JavaScript:
- First, create a
divwith the IDroot. - Use JavaScript to append an
h1tag to thediv.
- First, create a
<div id="root"></div>
<script>
const rootElement = document.getElementById('root');
const heading = document.createElement('h1');
heading.innerText = 'Hello World from JavaScript!';
rootElement.appendChild(heading);
</script>- Include React using CDN links to load the required scripts:
- `react.development.js` (Core React framework)
- `react-dom.development.js` (DOM manipulation with React)
<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 an `h1` element using React:
const heading = React.createElement('h1', {}, 'Hello World from React!');- Use `ReactDOM.createRoot()` to render the React element into the `root` div:
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(heading);- We can create nested elements in React by using `React.createElement()` recursively:
const parent = React.createElement(
'div', { id: 'parent' },
React.createElement(
'div', { id: 'child' },
React.createElement('h1', {}, 'This is an H1 tag inside a child div')
)
);
root.render(parent);- To add siblings to the structure, use arrays inside `React.createElement()`:
const parent = React.createElement(
'div', { id: 'parent' },
[
React.createElement('div', { id: 'child1' }, [
React.createElement('h1', {}, 'First Title from React! 1'),
React.createElement('h1', {}, 'Second Title from React! 1'),
]),
React.createElement('div', { id: 'child2' }, [
React.createElement('h1', {}, 'First Title from React! 2'),
React.createElement('h1', {}, 'Second Title from React! 2'),
])
]
);
root.render(parent);- Using `React.createElement()` can get messy, especially with nested elements.
- JSX simplifies the syntax, making your code more readable and intuitive.
- React manipulates only the portion of the DOM where it is mounted, allowing partial updates rather than re-rendering the entire page.
- React Elements are just JavaScript objects.
- React uses the Virtual DOM to efficiently update the UI.
- JSX makes writing React components easier by letting you use HTML-like syntax within JavaScript.