Table of Contents
- What is React?
- Prerequisites
- Setting Up Your Development Environment
- Your First React App: “Hello World”
- Understanding React Components
- Props: Passing Data to Components
- State: Managing Dynamic Data
- Event Handling in React
- Conditional Rendering
- Lists and Keys
- Forms in React
- Lifting State Up
- Deploying Your React App
- References
1. What is React?
React is a declarative, component-based JavaScript library for building user interfaces. Let’s break that down:
- Declarative: Instead of manually manipulating the DOM (e.g., with
document.getElementById), React lets you describe how your UI should look based on data, and it handles updating the DOM automatically when data changes. - Component-Based: UIs are built using reusable, independent “components” (e.g., buttons, forms, cards). Components can be nested, combined, and reused across your app, making code maintainable and scalable.
- Virtual DOM: React uses a lightweight in-memory copy of the DOM (Virtual DOM) to optimize rendering. When data changes, React updates the Virtual DOM first, compares it with the real DOM, and only applies the necessary changes (a process called “reconciliation”), improving performance.
2. Prerequisites
Before diving into React, ensure you have basic knowledge of:
- HTML/CSS: To structure and style UI elements.
- JavaScript (ES6+): Familiarity with arrow functions, destructuring, template literals,
let/const, and modules will help. - Command Line: Basic navigation (e.g.,
cd,ls) and package management (e.g.,npm).
You’ll also need:
- A code editor (e.g., VS Code with the ES7+ React Snippets extension for faster development).
- Node.js (v14.0.0 or later) and npm (v6.0.0 or later) to run and manage React projects.
3. Setting Up Your Development Environment
React projects can be set up manually, but the easiest way is using Create React App (CRA)—a tool built by Facebook to bootstrap React apps with zero configuration.
Step 1: Install Node.js and npm
If you don’t have Node.js installed, download it from nodejs.org. npm is included with Node.js. Verify installation by running:
node -v # Should output a version (e.g., v20.10.0)
npm -v # Should output a version (e.g., 10.2.3)
Step 2: Create a New React App
Open your terminal and run:
npx create-react-app my-first-react-app
npx(included with npm 5.2+) runs thecreate-react-apppackage without installing it globally.- Replace
my-first-react-appwith your project name (no spaces or special characters).
Step 3: Navigate to the Project and Start the Dev Server
cd my-first-react-app # Move into the project folder
npm start # Start the development server
Your app will launch at http://localhost:3000 in your browser. You’ll see a default React welcome page—congrats, you’ve built your first React app!
4. Your First React App: “Hello World”
Let’s simplify the default app to a classic “Hello World” example.
Project Structure Overview
CRA generates a project with this structure (key files highlighted):
my-first-react-app/
├── node_modules/ # Dependencies (auto-generated)
├── public/ # Static files (HTML, images)
│ └── index.html # Main HTML file (React injects UI here)
├── src/ # Source code
│ ├── App.js # Root component
│ ├── index.js # Entry point (renders App to DOM)
│ └── index.css # Global styles
├── package.json # Project metadata and scripts
└── README.md # Documentation
Modify App.js
Open src/App.js and replace its contents with:
function App() {
return (
<div className="App">
<h1>Hello, React!</h1>
</div>
);
}
export default App;
Save the file. The browser will auto-reload, and you’ll see “Hello, React!” displayed.
Understanding JSX
The code inside return() is JSX (JavaScript XML), a syntax extension for JavaScript that lets you write HTML-like code in React.
Key JSX rules:
- Single Root Element: JSX expressions must return a single root element (e.g., wrap elements in a
<div>or<React.Fragment>/<> </>for no extra DOM node). - className Instead of class: HTML’s
classattribute is a reserved word in JavaScript, so useclassNamein JSX:<div className="header">...</div> {/* Correct */} <div class="header">...</div> {/* Incorrect */} - Self-Closing Tags: Elements like
<img>,<input>, or custom components must close with/>:<img src="logo.png" alt="Logo" /> - JavaScript Expressions: Embed dynamic values using
{ }(curly braces):<h1>Hello, {name}!</h1> {/* Renders "Hello, Alice!" if name = "Alice" */}
5. Understanding React Components
Components are the building blocks of React apps. There are two types: functional components (modern, preferred) and class components (older syntax). We’ll focus on functional components.
Functional Components
A functional component is a JavaScript function that returns JSX.
Example: Create a Greeting component
Create a new file src/components/Greeting.js:
function Greeting() {
return <h2>Welcome to My React App!</h2>;
}
export default Greeting; // Export to use in other files
Import and use it in App.js:
import Greeting from './components/Greeting';
function App() {
return (
<div className="App">
<h1>Hello, React!</h1>
<Greeting /> {/* Use the Greeting component */}
</div>
);
}
export default App;
Now the browser shows both “Hello, React!” and “Welcome to My React App!“.
6. Props: Passing Data to Components
Props (short for “properties”) let you pass data from a parent component to a child component. They are read-only (children can’t modify props directly).
Example: Pass a name Prop to Greeting
Update Greeting.js to accept a name prop:
function Greeting(props) {
return <h2>Welcome, {props.name}!</h2>; {/* Use props.name */}
}
export default Greeting;
Pass the name prop from App.js:
import Greeting</think>
#</think></think></think># Getting Started with React</think></think></think># Getting Started with React: A Comprehensive Tutorial
## Introduction
In the fast-paced world of web development, React has emerged as a dominant force for building dynamic, interactive user interfaces (UIs). Developed by Facebook (now Meta) in 2013, React is an open-source JavaScript library that revolutionizes how we create web applications by emphasizing **component-based architecture**, reusability, and declarative programming.
Whether you’re a beginner looking to break into front-end development or an experienced developer transitioning to modern tools, React is a must-learn skill. Its popularity stems from its ability to simplify complex UIs, improve performance via the Virtual DOM, and seamlessly integrate with other libraries or frameworks (e.g., Redux for state management, React Router for navigation).
This tutorial is designed to take you from React novice to confidently building your first app. We’ll cover everything from setup to deployment, with hands-on examples and clear explanations. Let’s dive in!
## Table of Contents
1. [What is React?](#1-what-is-react)
2. [Prerequisites](#2-prerequisites)
3. [Setting Up Your Development Environment](#3-setting-up-your-development-environment)
4. [Your First React App: "Hello World"](#4-your-first-react-app-hello-world)
5. [Understanding React Components](#5-understanding-react-components)
6. [Props: Passing Data to Components](#6-props-passing-data-to-components)
7. [State: Managing Dynamic Data](#7-state-managing-dynamic-data)
8. [Event Handling in React](#8-event-handling-in-react)
9. [Conditional Rendering](#9-conditional-rendering)
10. [Lists and Keys](#10-lists-and-keys)
11. [Forms in React](#11-forms-in-react)
12. [Lifting State Up](#12-lifting-state-up-sharing-state-between-components)
13. [Deploying Your React App](#13-deploying-your-react-app)
14. [References](#14-references)
## 1. What is React?
React is a **declarative, component-based JavaScript library** for building user interfaces. Let’s break that down:
- **Declarative**: Instead of manually manipulating the DOM (e.g., with `document.getElementById`), React lets you describe *how* your UI should look based on data, and it handles updating the DOM automatically when data changes.
- **Component-Based**: UIs are built using reusable, independent "components" (e.g., buttons, forms, cards). Components can be nested, combined, and reused across your app, making code maintainable and scalable.
- **Virtual DOM**: React uses a lightweight in-memory copy of the DOM (Virtual DOM) to optimize rendering. When data changes, React updates the Virtual DOM first, compares it with the real DOM, and only applies the necessary changes (a process called "reconciliation"), improving performance.
## 2. Prerequisites
Before diving into React, ensure you have basic knowledge of:
- **HTML/CSS**: To structure and style UI elements.
- **JavaScript (ES6+)**: Familiarity with arrow functions, destructuring, template literals, `let`/`const`, and modules will help.
- **Command Line**: Basic navigation (e.g., `cd`, `ls`) and package management (e.g., `npm`).
You’ll also need:
- A code editor (e.g., [VS Code](https://code.visualstudio.com/) with the [ES7+ React Snippets](https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets) extension for faster development).
- [Node.js](https://nodejs.org/) (v14.0.0 or later) and [npm](https://www.npmjs.com/) (v6.0.0 or later) to run and manage React projects.
## 3. Setting Up Your Development Environment
React projects can be set up manually, but the easiest way is using **Create React App (CRA)**—a tool built by Facebook to bootstrap React apps with zero configuration.
### Step 1: Install Node.js and npm
If you don’t have Node.js installed, download it from [nodejs.org](https://nodejs.org/). npm is included with Node.js. Verify installation by running:
```bash
node -v # Should output a version (e.g., v20.10.0)
npm -v # Should output a version (e.g., 10.2.3)
Step 2: Create a New React App
Open your terminal and run:
npx create-react-app my-first-react-app
npx(included with npm 5.2+) runs thecreate-react-apppackage without installing it globally.- Replace
my-first-react-appwith your project name (no spaces or special characters).
Step 3: Navigate to the Project and Start the Dev Server
cd my-first-react-app # Move into the project folder
npm start # Start the development server
Your app will launch at http://localhost:3000 in your browser. You’ll see a default React welcome page—congrats, you’ve built your first React app!
4. Your First React App: “Hello World”
Let’s simplify the default app to a classic “Hello World” example.
Project Structure Overview
CRA generates a project with this structure (key files highlighted):
my-first-react-app/
├── node_modules/ # Dependencies (auto-generated)
├── public/ # Static files (HTML, images)
│ └── index.html # Main HTML file (React injects UI here)
├── src/ # Source code
│ ├── App.js # Root component
│ ├── index.js # Entry point (renders App to DOM)
│ └── index.css # Global styles
├── package.json # Project metadata and scripts
└── README.md # Documentation
Modify App.js
Open src/App.js and replace its contents with:
function App() {
return (
<div className="App">
<h1>Hello, React!</h1>
</div>
);
}
export default App;
Save the file. The browser will auto-reload, and you’ll see “Hello, React!” displayed.
Understanding JSX
The code inside return() is JSX (JavaScript XML), a syntax extension for JavaScript that lets you write HTML-like code in React.
Key JSX rules:
- Single Root Element: JSX expressions must return a single root element (e.g., wrap elements in a
<div>or<React.Fragment>/<> </>for no extra DOM node). - className Instead of class: HTML’s
classattribute is a reserved word in JavaScript, so useclassNamein JSX:<div className="header">...</div> {/* Correct */} <div class="header">...</div> {/* Incorrect */} - Self-Closing Tags: Elements like
<img>,<input>, or custom components must close with/>:<img src="logo.png" alt="Logo" /> - JavaScript Expressions: Embed dynamic values using
{ }(curly braces):<h1>Hello, {name}!</h1> {/* Renders "Hello, Alice!" if name = "Alice" */}
5. Understanding React Components
Components are the building blocks of React apps. There are two types: functional components (modern, preferred) and class components (older syntax). We’ll focus on functional components.
Functional Components
A functional component is a JavaScript function that returns JSX.
Example: Create a Greeting component
Create a new file src/components/Greeting.js:
function Greeting() {
return <h2>Welcome to My React App!</h2>;
}
export default Greeting; // Export to use in other files
Import and use it in App.js:
import Greeting from './components/Greeting';
function App() {
return (
<div className="App">
<h1>Hello, React!</h1>
<Greeting /> {/* Use the Greeting component */}
</div>
);
}
export default App;
Now the browser shows both “Hello, React!” and “Welcome to My React App!“.
6. Props: Passing Data to Components
Props (short for “properties”) let you pass data from a parent component to a child component. They are read-only (children can’t modify props directly).
Example: Pass a name Prop to Greeting
Update Greeting.js to accept a name prop:
function Greeting(props) {
return <h2>Welcome, {props.name}!</h2>; {/* Use props.name */}
}
export default Greeting;
Pass the name prop from App.js:
import Greeting from './components/Greeting';
function App() {
return (
<div className="App">
<h1>Hello, React!</h1>
<Greeting name="Alice" /> {/* Pass prop: name="Alice" */}
</div>
);
}
The browser now displays “Welcome, Alice!“.
Destructuring Props
For cleaner code, destructure props directly in the function parameters:
function Greeting({ name }) { {/* Destructure name from props */}
return <h2>Welcome, {name}!</h2>;
}
7. State: Managing Dynamic Data
State is used to store and manage dynamic data within a component (e.g., user input, toggle switches, counters). Unlike props (passed from parents), state is owned and updated by the component itself.
React provides the useState hook (a special function) to add state to functional components.
Example: Counter Component with useState
Create src/components/Counter.js:
import { useState } from 'react'; {/* Import useState hook */}
function Counter() {
// Declare state variable: count (initial value 0) and setter function: setCount
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default Counter;
Import and use Counter in App.js. Clicking the buttons will update the count dynamically!
How useState Works:
const [count, setCount] = useState(0):count: The state variable (current value).setCount: A function to updatecount(never modify state directly:count = count + 1is invalid!).useState(0): Initializescountto0.
8. Event Handling in React
React events (e.g., onClick, onChange) are similar to HTML events but use camelCase (e.g., onclick → onClick). Event handlers are functions that run when an event occurs.
Example: Toggle Button
Create src/components/Toggle.js:
import { useState } from 'react';
function Toggle() {
const [isOn, setIsOn] = useState(false);
const handleToggle = () => {
setIsOn(!isOn); {/* Flip the boolean value */}
};
return (
<button onClick={handleToggle}> {/* Attach handler to onClick */}
{isOn ? 'ON' : 'OFF'} {/* Display "ON" or "OFF" based on state */}
</button>
);
}
export default Toggle;
onClick={handleToggle}: Attaches thehandleTogglefunction to the button click event (no parentheses—we pass the function, not its result).
9. Conditional Rendering
Conditional rendering lets you display different UI elements based on state or props. Common methods:
1. Ternary Operator
function UserGreeting({ isLoggedIn }) {
return isLoggedIn ? (
<h2>Welcome back!</h2>
) : (
<h2>Please sign in.</h2>
);
}
2. Logical && Operator
Render content only if a condition is true:
function Notification({ hasUnreadMessages }) {
return (
<div>
<h1>My App</h1>
{hasUnreadMessages && <p>You have unread messages!</p>} {/* Renders only if hasUnreadMessages is true */}
</div>
);
}
3. If/Else (Outside JSX)
function Greeting({ time }) {
let message;
if (time < 12) {
message = 'Good morning';
} else if (time < 18) {
message = 'Good afternoon';
} else {
message = 'Good evening';
}
return <h2>{message}!</h2>;
}
10. Lists and Keys
To render lists (e.g., arrays of data), use the map method. Each list item needs a unique key prop to help React identify changes efficiently.
Example: Render a List of Items
function TodoList() {
const todos = [
{ id: 1, text: 'Learn React' },
{ id: 2, text: 'Build an app' },
{ id: 3, text: 'Deploy!' }
];
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li> {/* key must be unique */}
))}
</ul>
);
}
Why Keys?
Keys help React track which items are added, removed, or reordered. Always use a unique identifier (e.g., id from a database). Avoid using array indexes as keys (they can cause bugs if the list is reordered).
11. Forms in React
React forms differ from HTML forms: React controls form data via state (controlled components), rather than the DOM.
Controlled Component Example (Text Input)
import { useState } from 'react';
function NameForm() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault(); {/* Prevent default form submission (page reload) */}
alert(`Hello, ${name}!`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name} {/* Value tied to state */}
onChange={(e) => setName(e.target.value)} {/* Update state on input */}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
value={name}: The input’s value is controlled by thenamestate.onChange={(e) => setName(e.target.value)}: Updatesnamestate with user input.
12. Lifting State Up: Sharing State Between Components
When two or more components need to share state (e.g., a parent and child, or siblings), move the state to their closest common parent. This is called “lifting state up.”
Example: Temperature Converter (Celsius ↔ Fahrenheit)
import { useState } from 'react';
// Child component: Input for temperature
function TemperatureInput({ scale, value, onChange }) {
return (
<input
type="number"
value={value}
onChange={(e) => onChange(scale, e.target.value)} {/* Pass scale and value to parent */}
placeholder={`Enter ${scale}`}
/>
);
}
// Parent component: Manages shared state
function TemperatureConverter() {
const [temperature, setTemperature] = useState({ celsius: '', fahrenheit: '' });
const handleChange = (scale, value) => {
setTemperature({ ...temperature, [scale]: value });
// Add logic to convert between scales (omitted for brevity)
};
return (
<div>
<TemperatureInput
scale="celsius"
value={temperature.celsius}
onChange={handleChange} {/* Pass handler to child */}
/>
<TemperatureInput
scale="fahrenheit"
value={temperature.fahrenheit}
onChange={handleChange}
/>
</div>
);
}
13. Deploying Your React App
Once your app is ready, deploy it to share with the world! Popular options:
Option 1: Netlify (Free, Easy)
- Push your project to GitHub (create a repo and run
git push). - Go to Netlify and sign up with GitHub.
- Click “Add new site” → “Import an existing project” → Select your GitHub repo.
- Set build command:
npm run buildand publish directory:build. - Click “Deploy site”—your app will be live in minutes!
Option 2: Vercel (React-Focused)
Similar to Netlify, but optimized for React. Connect your GitHub repo, and Vercel auto-detects React apps for one-click deployment.
14. References
- React Official Docs: react.dev (best resource for learning React).
- Create React App: create-react-app.dev (setup and scripts).
- MDN JavaScript Guide: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide (brush up on JS).
- React Hooks Cheat Sheet: react-hooks-cheatsheet.com (quick reference for hooks like
useStateanduseEffect).
You now have a solid foundation in React! From components and props to state management and deployment, you’re ready to build interactive UIs. Keep practicing by building small projects (e.g., to-do apps, calculators) and exploring advanced topics like React Router (routing), Redux (state management), or custom hooks. Happy coding! 🚀