⚛️ Getting Started with React: Building Your First Component
⚛️ Getting Started with React: Building Your First Component
When I first heard about React, I thought it was this complex, enterprise-level framework that only senior developers could understand. Components? Props? State? Hooks? It all sounded like a foreign language.
But here's what I wish someone had told me: React is just a way to build reusable pieces of your website. That's it. Everything else builds from that simple idea.
What is React, Really?
Think of React like LEGO blocks:
- LEGO blocks = Components
- Different colored blocks = Different components
- Building something = Combining components
Instead of writing one giant HTML file, you break your website into small, reusable pieces called "components." Each component does one thing well.
Why React?
Before React, updating a webpage meant:
- Finding the right HTML element
- Changing it with JavaScript
- Hoping nothing broke
- Repeating for every change
With React:
- You describe what your UI should look like
- React figures out what changed
- Only updates what's necessary
- Much faster and cleaner!
Setting Up React
Option 1: Create React App (Simplest)
npx create-react-app my-first-app cd my-first-app npm start
That's it! Your React app is running.
Option 2: Next.js (Recommended for Modern Projects)
npx create-next-app@latest my-app cd my-app npm run dev
Next.js is built on React but includes routing, server-side rendering, and more features.
Option 3: Vite (Fastest)
npm create vite@latest my-app -- --template react cd my-app npm install npm run dev
Pick whichever feels comfortable. For beginners, Create React App is the simplest.
Understanding Components
A component is just a JavaScript function that returns HTML (called JSX).
Your First Component
function Welcome() { return <h1>Hello, World!</h1>; } // Use it function App() { return ( <div> <Welcome /> <Welcome /> <Welcome /> </div> ); }
See? One component (Welcome), used three times. That's the power of React!
Component Rules
-
Component names start with a capital letter
// ✅ Good function MyComponent() {} // ❌ Bad function myComponent() {} -
Return one element (or wrap multiple in a fragment)
// ✅ Good return ( <div> <h1>Title</h1> <p>Content</p> </div> ); // ✅ Also good (fragment) return ( <> <h1>Title</h1> <p>Content</p> </> ); -
Use JSX syntax (HTML-like but in JavaScript)
// ✅ Good return <div className="container">Content</div>; // ❌ Bad (class is reserved in JavaScript) return <div class="container">Content</div>;
Props: Passing Data to Components
Props are like function parameters, but for components.
Basic Props
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } // Use it <Greeting name="Sarah" /> // Output: Hello, Sarah!
Destructuring Props (Cleaner)
function Greeting({ name, age }) { return ( <div> <h1>Hello, {name}!</h1> <p>You are {age} years old.</p> </div> ); } // Use it <Greeting name="Sarah" age={25} />
Real Example: User Card
function UserCard({ name, email, avatar }) { return ( <div className="user-card"> <img src={avatar} alt={name} /> <h2>{name}</h2> <p>{email}</p> </div> ); } // Use it <UserCard name="John Doe" email="john@example.com" avatar="/images/john.jpg" />
State: Making Components Interactive
State is data that can change. When state changes, React automatically updates the UI.
useState Hook
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
Let's break this down:
useState(0)- Creates state starting at 0count- The current valuesetCount- Function to update the valueonClick- Runs when button is clicked
Real Example: Toggle Button
function ThemeToggle() { const [isDark, setIsDark] = useState(false); return ( <button onClick={() => setIsDark(!isDark)}> {isDark ? 'Switch to Light' : 'Switch to Dark'} </button> ); }
Example: Input Field
function NameInput() { const [name, setName] = useState(''); return ( <div> <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter your name" /> <p>Hello, {name || 'stranger'}!</p> </div> ); }
Building Your First Real Component
Let's build a Todo List component:
import { useState } from 'react'; function TodoList() { const [todos, setTodos] = useState([]); const [input, setInput] = useState(''); const addTodo = () => { if (input.trim()) { setTodos([...todos, input]); setInput(''); } }; return ( <div> <h1>My Todo List</h1> <input value={input} onChange={(e) => setInput(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && addTodo()} placeholder="Add a todo..." /> <button onClick={addTodo}>Add</button> <ul> {todos.map((todo, index) => ( <li key={index}>{todo}</li> ))} </ul> </div> ); }
Event Handling
React makes handling events simple:
function Button() { const handleClick = () => { alert('Button clicked!'); }; return <button onClick={handleClick}>Click me</button>; }
Common Events
onClick- Mouse clickonChange- Input changeonSubmit- Form submissiononKeyPress- Keyboard pressonMouseEnter- Mouse enters element
Conditional Rendering
Show different content based on conditions:
function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } return <h1>Please log in.</h1>; } // Or with ternary function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? ( <h1>Welcome back!</h1> ) : ( <h1>Please log in.</h1> )} </div> ); }
Lists and Keys
Rendering lists:
function UserList({ users }) { return ( <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } // Use it const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]; <UserList users={users} />
Important: Always use key prop when rendering lists. It helps React track changes efficiently.
useEffect: Running Code After Render
Use useEffect to run code after component renders:
import { useState, useEffect } from 'react'; function Clock() { const [time, setTime] = useState(new Date()); useEffect(() => { const timer = setInterval(() => { setTime(new Date()); }, 1000); // Cleanup return () => clearInterval(timer); }, []); return <div>{time.toLocaleTimeString()}</div>; }
Common Patterns
Controlled Components
function SearchInput() { const [query, setQuery] = useState(''); return ( <input value={query} onChange={(e) => setQuery(e.target.value)} /> ); }
Lifting State Up
When multiple components need the same data:
function App() { const [count, setCount] = useState(0); return ( <div> <Display count={count} /> <Buttons setCount={setCount} /> </div> ); }
Your Learning Path
Week 1: Basics
- ✅ Create your first React app
- ✅ Build simple components
- ✅ Understand props
- ✅ Use basic state
Week 2: Interactivity
- ✅ Handle events
- ✅ Build forms
- ✅ Conditional rendering
- ✅ Render lists
Week 3: Advanced Concepts
- ✅ useEffect hook
- ✅ Custom hooks
- ✅ Context API
- ✅ Build a project
Week 4: Practice
- ✅ Build multiple projects
- ✅ Learn React Router
- ✅ Deploy your app
- ✅ Keep learning!
Common Mistakes to Avoid
1. Mutating State Directly
// ❌ Bad const [items, setItems] = useState([]); items.push('new item'); // ✅ Good setItems([...items, 'new item']);
2. Forgetting Keys in Lists
// ❌ Bad {todos.map(todo => <li>{todo}</li>)} // ✅ Good {todos.map((todo, index) => <li key={index}>{todo}</li>)}
3. Using class Instead of className
// ❌ Bad <div class="container"> // ✅ Good <div className="container">
Project Ideas
- Counter App - Learn state
- Todo List - Learn state and lists
- Weather App - Learn API integration
- Blog - Learn routing
- Quiz App - Learn complex state
The Bottom Line
React is just:
- Components = Reusable UI pieces
- Props = Data passed to components
- State = Data that changes
- Hooks = Functions that add features
Start simple. Build small components. Combine them. Before you know it, you'll be building complex applications!
Remember: Every React expert started with their first component. You've got this! 🚀
Now go create your first React app and start building!