⏱️ Duration : 20 minutes | Learn how React revolutionizes UI development.
What is React?
React is a JavaScript library for building user interfaces. It lets you create reusable components that manage their own state.
Ever noticed how Netflix updates smoothly without reloading the whole page? That’s React! 🎬
Fun Fact : React was created by Meta (Facebook) in 2013 and now powers billions of users on Facebook, Instagram, and WhatsApp! The engineer who created it, Jordan Walke, built the first version in just a few weeks!
Why React?
Traditional Approach React Approach Manually update HTML Components update automatically Copy-paste code Reusable components Hard to track state Clear state management DOM manipulation Declarative UI
React Official Tutorial Learn React step-by-step with the official interactive tutorial
Components
Components are the building blocks of React apps. Think of them as custom HTML elements.
Your First Component
// A simple component
function Greeting () {
return < h1 > Hello, World! </ h1 > ;
}
// Using the component
function App () {
return (
< div >
< Greeting />
< Greeting />
< Greeting />
</ div >
);
}
Beginner Tip : Component names must start with a capital letter! Greeting not greeting.
JSX: HTML in JavaScript
JSX lets you write HTML-like code in JavaScript:
function WelcomeCard () {
const name = "Alice" ;
const isStudent = true ;
return (
< div className = "card" >
< h2 > Welcome, { name } ! </ h2 >
{ isStudent && < p > Student discount available! </ p > }
</ div >
);
}
JSX Rules
HTML JSX classclassNameforhtmlForstyle="color: red"style={{ color: 'red' }}Self-closing: <img> Must close: <img />
Props: Passing Data
Props let you pass data to components:
// Component that accepts props
interface UserCardProps {
name : string ;
age : number ;
isActive ?: boolean ;
}
function UserCard ({ name , age , isActive = false } : UserCardProps ) {
return (
< div className = "p-4 bg-white rounded-lg shadow" >
< h3 className = "font-bold" > { name } </ h3 >
< p > Age: { age } </ p >
{ isActive && < span className = "text-green-500" > ● Online </ span > }
</ div >
);
}
// Using the component with props
function App () {
return (
< div className = "space-y-4" >
< UserCard name = "Alice" age = { 20 } isActive />
< UserCard name = "Bob" age = { 22 } />
< UserCard name = "Charlie" age = { 19 } isActive />
</ div >
);
}
State: Making Things Interactive
State is data that changes over time. Use useState to add state:
import { useState } from 'react' ;
function Counter () {
// Declare state: [value, setterFunction]
const [ count , setCount ] = useState ( 0 );
return (
< div className = "text-center" >
< p className = "text-4xl font-bold" > { count } </ p >
< div className = "flex gap-2 justify-center mt-4" >
< button
onClick = { () => setCount ( count - 1 ) }
className = "px-4 py-2 bg-red-500 text-white rounded"
>
-1
</ button >
< button
onClick = { () => setCount ( count + 1 ) }
className = "px-4 py-2 bg-green-500 text-white rounded"
>
+1
</ button >
</ div >
</ div >
);
}
Try it yourself! 👇
Important : Never modify state directly! Always use the setter function.// ❌ Wrong
count = count + 1 ;
// ✅ Correct
setCount ( count + 1 );
Handling Events
React makes event handling easy:
function LoginForm () {
const [ email , setEmail ] = useState ( '' );
const [ password , setPassword ] = useState ( '' );
const handleSubmit = ( e : React . FormEvent ) => {
e . preventDefault (); // Prevent page refresh
console . log ( 'Logging in:' , email );
};
return (
< form onSubmit = { handleSubmit } className = "space-y-4" >
< input
type = "email"
value = { email }
onChange = { ( e ) => setEmail ( e . target . value ) }
placeholder = "Email"
className = "w-full p-2 border rounded"
/>
< input
type = "password"
value = { password }
onChange = { ( e ) => setPassword ( e . target . value ) }
placeholder = "Password"
className = "w-full p-2 border rounded"
/>
< button
type = "submit"
className = "w-full p-2 bg-blue-500 text-white rounded"
>
Login
</ button >
</ form >
);
}
Rendering Lists
Use .map() to render arrays of components:
interface Todo {
id : number ;
title : string ;
completed : boolean ;
}
function TodoList () {
const [ todos , setTodos ] = useState < Todo []>([
{ id: 1 , title: 'Learn React' , completed: true },
{ id: 2 , title: 'Build an app' , completed: false },
{ id: 3 , title: 'Deploy to Vercel' , completed: false },
]);
return (
< ul className = "space-y-2" >
{ todos . map (( todo ) => (
< li
key = { todo . id }
className = { `p-3 rounded ${
todo . completed ? 'bg-green-100' : 'bg-gray-100'
} ` }
>
{ todo . completed ? '✅' : '⬜' } { todo . title }
</ li >
)) }
</ ul >
);
}
Beginner Tip : Always add a unique key prop when rendering lists. Use IDs, not array indices.
Conditional Rendering
Show different content based on conditions:
function UserStatus ({ isLoggedIn } : { isLoggedIn : boolean }) {
// Method 1: Ternary operator
return (
< div >
{ isLoggedIn ? (
< p > Welcome back! </ p >
) : (
< p > Please log in. </ p >
) }
</ div >
);
}
function Notification ({ count } : { count : number }) {
// Method 2: && operator (render if true)
return (
< div >
{ count > 0 && (
< span className = "bg-red-500 text-white px-2 rounded-full" >
{ count }
</ span >
) }
</ div >
);
}
Try it! 👇 Toggle login state:
Complete Example: Task Manager
import { useState } from 'react' ;
interface Task {
id : number ;
text : string ;
done : boolean ;
}
function TaskManager () {
const [ tasks , setTasks ] = useState < Task []>([]);
const [ input , setInput ] = useState ( '' );
const addTask = () => {
if ( ! input . trim ()) return ;
setTasks ([
... tasks ,
{ id: Date . now (), text: input , done: false }
]);
setInput ( '' );
};
const toggleTask = ( id : number ) => {
setTasks ( tasks . map ( task =>
task . id === id ? { ... task , done: ! task . done } : task
));
};
return (
< div className = "max-w-md mx-auto p-6" >
< h1 className = "text-2xl font-bold mb-4" > Tasks </ h1 >
{ /* Add task */ }
< div className = "flex gap-2 mb-4" >
< input
value = { input }
onChange = { ( e ) => setInput ( e . target . value ) }
onKeyDown = { ( e ) => e . key === 'Enter' && addTask () }
placeholder = "New task..."
className = "flex-1 p-2 border rounded"
/>
< button
onClick = { addTask }
className = "px-4 py-2 bg-blue-500 text-white rounded"
>
Add
</ button >
</ div >
{ /* Task list */ }
< ul className = "space-y-2" >
{ tasks . map (( task ) => (
< li
key = { task . id }
onClick = { () => toggleTask ( task . id ) }
className = { `p-3 rounded cursor-pointer ${
task . done
? 'bg-green-100 line-through text-gray-500'
: 'bg-gray-100'
} ` }
>
{ task . text }
</ li >
)) }
</ ul >
</ div >
);
}
Try it! 👇 Add tasks and click to toggle:
React Cheat Sheet
Concept Syntax Component function Name() { return <div>...</div> }Props function Card({ title }: { title: string })State const [value, setValue] = useState(initial)Event onClick={() => doSomething()}List {items.map(item => <li key={item.id}>...</li>)}Conditional {condition && <Component />}
Next up : Next.js →