React - The Basics
What is React?
React is a JavaScript library (not really a framework) created by Facebook for building user interfaces.
Why React?
- Component-based: we break everything down into small, reusable blocks
- Declarative: we say what we want, not how to do it
- Huge ecosystem: everything already exists, or almost
- Job market: it's the most in-demand on the market
see https://2024.stateofjs.com/en-US
Quick Setup with Vite
npm create vite@latest my-app -- --template react
cd my-app
npm install
npm run dev
And there you go! Your React app is running on localhost:5173
The 3 Essential Concepts
1. Components
function MyComponent() {
return <h1>Hello World!</h1>
}
2. State (useState)
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
)
}
3. Props
function Greeting({ name }) {
return <h1>Hello {name}!</h1>
}
// Usage
<Greeting name="Andy" />
JSX in 30 Seconds
- HTML in JavaScript
className
instead ofclass
{}
to inject JS- Always close tags
function App() {
const name = "Andy"
return (
<div className="container">
<h1>Hello {name}!</h1>
<img src="photo.jpg" alt="Photo" />
</div>
)
}
Concrete Example: Todo List
import { useState } from 'react'
function TodoList() {
const [todos, setTodos] = useState([])
const [input, setInput] = useState('')
const add = () => {
if (input.trim()) {
setTodos([...todos, { id: Date.now(), text: input }])
setInput('')
}
}
return (
<div>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="New task..."
/>
<button onClick={add}>Add</button>
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
</div>
)
}
Go Further
Complete Roadmap: https://roadmap.sh/react
Official Documentation: https://react.dev/learn