Components that react
React is a library for building user interfaces with reusable components.
Key concepts
| Concept | What it is |
|---|---|
| Component | Reusable UI piece |
| Props | Data the component receives |
| State | Internal component data |
| Hook | Function to add functionality |
Your first component
// Functional component
function Greeting({ name }: { name: string }) {
return <h1>Hello, {name}!</h1>
}
// Usage
<Greeting name="Ana" />
useState: Local state
import { useState } from 'react'
function Counter() {
const [count, setCount] = useState(0)
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
+1
</button>
</div>
)
}
useEffect: Side effects
import { useState, useEffect } from 'react'
function Data() {
const [data, setData] = useState(null)
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData)
}, []) // [] = only on mount
return <div>{JSON.stringify(data)}</div>
}
Common pattern: List
interface Item {
id: string
name: string
}
function List({ items }: { items: Item[] }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)
}
Forms
function Form() {
const [text, setText] = useState('')
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
console.log('Submitted:', text)
}
return (
<form onSubmit={handleSubmit}>
<input
value={text}
onChange={e => setText(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
)
}
Practice
Useful links
- ๐ React Docs
- ๐ React Tutorial