React ek JavaScript library hai jo user interfaces (UI) banane ke liye use hoti hai. Yeh Facebook ne develop ki thi aur ab open-source hai. React ka main focus fast, scalable, aur simple web applications banane par hota hai.
SPA ek aisi web application hai jo sirf ek HTML page load karti hai aur dynamically content update karti hai bina page reload kiye.
Feature | React | Vanilla JavaScript |
---|---|---|
Type | JavaScript Library | Plain JavaScript |
DOM Manipulation | Uses Virtual DOM (Fast) | Uses Real DOM (Slower) |
UI Structure | Component-Based Architecture | Manually manage karna hota hai |
Performance | Fast due to Virtual DOM | Slow due to direct DOM updates |
Reusability | Components can be reused | Code reuse difficult |
JSX ek syntax extension hai jo React ke andar HTML-like structure likhne ke liye use hota hai. Yeh JavaScript ke andar HTML likhne ki suvidha deta hai.
useState
is a React Hook that allows you to add state management to functional components. It helps store and update
values within a component, ensuring React re-renders the component whenever the state changes.
React does not track changes in normal variables, meaning updates won’t trigger a re-render of the
component.
useState
ensures that when a state value changes, React automatically updates the UI.
let count = 0;
function Example() {
function increase() {
count += 1;
console.log(count); // Updates in console, but UI doesn't update
}
return (
<div>
<p>Count: {count}</p> {/* UI remains the same */}
<button onClick={increase}>Increase</button>
</div>
);
}
The UI does not update when
count
changes because React does not track it.
import { useState } from "react";
function Example() {
const [count, setCount] = useState(0);
function increase() {
setCount(count + 1); // Updates state and re-renders the component
}
return (
<div>
<p>Count: {count}</p> {/* UI updates correctly */}
<button onClick={increase}>Increase</button>
</div>
);
}
Use Case: When we need to store and update input values in a form.
Use Case: When we need to toggle a feature on/off, such as showing/hiding a password.
Use Case: Tracking numbers such as likes, cart items, or steps.
const [state, setState] = useState(initialValue);
state
: The current value of the state.
setState
: The function used to update the state.
initialValue
: The initial state value (can be a number, string, boolean, object, or array).
const [count, setCount] = useState(0);
const [name, setName] = useState("abc");
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [user, setUser] = useState({ name: "John Doe", age: 30 });
const [items, setItems] = useState(["Apple", "Mango"]);
import { useState } from "react";
function UserForm() {
const [name, setName] = useState("");
const [age, setAge] = useState("");
return (
<div>
<input
type="text"
placeholder="Enter name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="number"
placeholder="Enter age"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
<h3>Name: {name}, Age: {age}</h3>
</div>
);
}
export default UserForm;
useState
variables ek saath kaise use karein.
onChange
event kaise kaam karta hai.
Whenever the new state depends on the previous state, we should always use the callback function inside
setState
.
React batches state updates, meaning multiple updates inside one function might not reflect immediately. If
we directly use
setState(value)
, React might not update it as expected. Instead, we should use the function version:
setState((prevState) => newValue);
This ensures we get the latest previous value before updating.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const incrementByTwo = () => {
setCount((prevCount) => prevCount + 2);
};
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={incrementByTwo}>Increment by 2</button>
</div>
);
}
export default Counter;
import { useState } from "react";
function TodoList() {
const [tasks, setTasks] = useState([]);
const addTask = () => {
setTasks([...tasks, `Task ${tasks.length + 1}`]);
};
return (
<div>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
</div>
);
}
export default TodoList;
import { useState } from "react";
function TodoList() {
const [tasks, setTasks] = useState([]);
const [task, setTask] = useState("");
// Function to add a new task
const addTask = () => {
if (task.trim() !== "") {
setTasks([...tasks, task]);
setTask(""); // Clear input field
}
};
// Function to remove a task
const removeTask = (index) => {
const updatedTasks = tasks.filter((_, i) => i !== index);
setTasks(updatedTasks);
};
return (
<div style={{ textAlign: "center", padding: "20px" }}>
<h2>To-Do List</h2>
<input
type="text"
placeholder="Enter a task"
value={task}
onChange={(e) => setTask(e.target.value)}
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((t, index) => (
<li key={index}>
{t} <button onClick={() => removeTask(index)}>❌</button>
</li>
))}
</ul>
</div>
);
}
export default TodoList;
import { useState } from "react";
function ThemeSwitcher() {
const [darkMode, setDarkMode] = useState(false);
return (
<div style={{ background: darkMode ? "black" : "white", color: darkMode ? "white" : "black", height: "100vh", textAlign: "center", padding: "50px" }}>
<h1>{darkMode ? "Dark Mode" : "Light Mode"}</h1>
<button onClick={() => setDarkMode(!darkMode)}>Toggle Theme</button>
</div>
);
}
export default ThemeSwitcher;
Components are the building blocks of a React application. They are reusable and independent pieces of code that represent a part of the user interface (UI). Each component can have its own state, logic, and structure.
React.Component
and have additional features like lifecycle methods.
Functional components are the simplest way to create a component. They are JavaScript functions that return JSX.
function Greeting() {
return <h1>Hello, World!</h1>;
}
export default Greeting;
useState
), functional components can now manage state.
Class components are ES6 classes that extend
React.Component
. They have additional features like state and lifecycle methods.
import React from "react";
class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
export default Greeting;
componentDidMount
,
componentDidUpdate
, etc.
Props are used to pass data from one component to another. They are read-only and help make components reusable and dynamic.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Greeting;
Usage:
import Greeting from "./Greeting";
function App() {
return (
<div>
<Greeting name="John" />
<Greeting name="Jane" />
</div>
);
}
export default App;
Default props are used to provide default values for props in case they are not passed from the parent component.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Greeting.defaultProps = {
name: "Guest",
};
export default Greeting;
Usage:
import Greeting from "./Greeting";
function App() {
return (
<div>
<Greeting /> {/* Output: Hello, Guest! */}
<Greeting name="John" /> {/* Output: Hello, John! */}
</div>
);
}
export default App;
PropTypes are used to validate the type of props passed to a component. They help catch bugs by ensuring that the correct data types are passed.
import PropTypes from "prop-types";
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
export default Greeting;
Functions can also be passed as props to child components. This allows child components to communicate with parent components.
function ChildComponent(props) {
return <button onClick={props.onClick}>Click Me</button>;
}
function ParentComponent() {
const handleClick = () => {
alert("Button clicked!");
};
return <ChildComponent onClick={handleClick} />;
}
export default ParentComponent;
Component composition is the process of combining smaller components to build more complex UIs. It promotes reusability and separation of concerns.
function Header() {
return <h1>Header</h1>;
}
function Content() {
return <p>This is the content.</p>;
}
function Footer() {
return <footer>Footer</footer>;
}
function App() {
return (
<div>
<Header />
<Content />
<Footer />
</div>
);
}
export default App;
Create a reusable
UserCard
component that displays user details (name, email, and profile picture) using props.
function UserCard(props) {
return (
<div style={{ border: "1px solid #ccc", padding: "10px", margin: "10px", borderRadius: "5px" }}>
<img src={props.avatar} alt="User Avatar" style={{ width: "100px", borderRadius: "50%" }} />
<h2>{props.name}</h2>
<p>{props.email}</p>
</div>
);
}
export default UserCard;
Usage:
import UserCard from "./UserCard";
function App() {
const user = {
name: "John Doe",
email: "john@example.com",
avatar: "https://via.placeholder.com/150",
};
return (
<div>
<UserCard name={user.name} email={user.email} avatar={user.avatar} />
</div>
);
}
export default App;
Event handling in React allows you to respond to user interactions like clicks, input changes, form
submissions, etc. React events are similar to DOM events but are written in camelCase (e.g.,
onClick
instead of
onclick
).
React supports a wide range of events. Here are some commonly used ones:
Event | Description |
---|---|
onClick
|
Triggered when an element is clicked. |
onChange
|
Triggered when the value of an input, select, or textarea changes. |
onSubmit
|
Triggered when a form is submitted. |
onMouseOver
|
Triggered when the mouse pointer moves over an element. |
onKeyDown
|
Triggered when a key is pressed down. |
In React, event handlers are passed as functions to the event attributes (e.g.,
onClick
,
onChange
). These functions are called when the event occurs.
function App() {
const handleClick = () => {
alert("Button clicked!");
};
return (
<div>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
export default App;
function App() {
const [inputValue, setInputValue] = useState("");
const handleChange = (event) => {
setInputValue(event.target.value);
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={handleChange}
placeholder="Type something..."
/>
<p>You typed: {inputValue}</p>
</div>
);
}
export default App;
Sometimes, you may need to pass additional arguments to an event handler. This can be done using an arrow function.
function App() {
const handleClick = (message) => {
alert(message);
};
return (
<div>
<button onClick={() => handleClick("Hello!")}>Say Hello</button>
<button onClick={() => handleClick("Goodbye!")}>Say Goodbye</button>
</div>
);
}
export default App;
In some cases, you may want to prevent the default behavior of an event (e.g., preventing a form from
submitting). This can be done using
event.preventDefault()
.
function App() {
const handleSubmit = (event) => {
event.preventDefault();
alert("Form submitted!");
};
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form>
);
}
export default App;
React uses synthetic events to wrap native browser events. These events work consistently across all browsers and provide additional features.
SyntheticEvent
.
event.target
,
event.preventDefault()
).
Create a button that toggles between "Show" and "Hide" text when clicked.
function App() {
const [showText, setShowText] = useState(true);
const toggleText = () => {
setShowText(!showText);
};
return (
<div>
<button onClick={toggleText}>{showText ? "Hide" : "Show"}</button>
{showText && <p>This is some text!</p>}
</div>
);
}
export default App;
Create a form with name and email fields. Validate that both fields are filled before allowing submission.
function App() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [error, setError] = useState("");
const handleSubmit = (event) => {
event.preventDefault();
if (!name || !email) {
setError("Please fill in all fields.");
} else {
setError("");
alert(`Name: ${name}, Email: ${email}`);
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button type="submit">Submit</button>
{error && <p style={{ color: "red" }}>{error}</p>}
</form>
);
}
export default App;
onClick
).
event.preventDefault()
to prevent default behavior.
map()
Function
The
map()
function is a powerful JavaScript method used to transform arrays. In React, it is
commonly used to render
dynamic lists
of components.
map()
Works
map()
iterates over an array and returns a new array.
map()
.
map()
function App() {
const fruits = ["Apple", "Banana", "Mango", "Orange"];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}
export default App;
When rendering lists in React, each element must have a unique key . Keys help React identify which items have changed, been added, or been removed.
function App() {
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" },
{ id: 3, name: "Alice" },
];
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
export default App;
id
) as the key.
index
as the key if the list can change (e.g., items can be added, removed, or reordered).
Dynamic lists are lists where the data is not static but can change over time (e.g., fetched from an API or updated by user input). React makes it easy to render and update dynamic lists.
import { useState } from "react";
function App() {
const [tasks, setTasks] = useState([]);
const [task, setTask] = useState("");
const addTask = () => {
if (task.trim() !== "") {
setTasks([...tasks, { id: Date.now(), text: task }]);
setTask("");
}
};
const removeTask = (id) => {
setTasks(tasks.filter((task) => task.id !== id));
};
return (
<div>
<input
type="text"
placeholder="Enter a task"
value={task}
onChange={(e) => setTask(e.target.value)}
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map((task) => (
<li key={task.id}>
{task.text} <button onClick={() => removeTask(task.id)}>❌</button>
</li>
))}
</ul>
</div>
);
}
export default App;
useState
to manage the list data.
map()
to render the list dynamically.
Create a dynamic list of users where you can add and remove users. Each user should have a name and an email.
import { useState } from "react";
function App() {
const [users, setUsers] = useState([]);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const addUser = () => {
if (name.trim() !== "" && email.trim() !== "") {
setUsers([...users, { id: Date.now(), name, email }]);
setName("");
setEmail("");
}
};
const removeUser = (id) => {
setUsers(users.filter((user) => user.id !== id));
};
return (
<div>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button onClick={addUser}>Add User</button>
<ul>
{users.map((user) => (
<li key={user.id}>
<strong>{user.name}</strong> - {user.email}
<button onClick={() => removeUser(user.id)}>❌</button>
</li>
))}
</ul>
</div>
);
}
export default App;
map()
function is used to transform arrays and render dynamic lists in React.
useState
and
map()
.
React Router DOM ek library hai jo React applications mein routing ko handle karti hai. Iska use Single Page Applications (SPAs) mein different pages ya components ko render karne ke liye kiya jata hai, bina page reload kiye.
React Router DOM ko use karne ke liye pehle ise install karna hoga:
npm install react-router-dom
React Router DOM ka basic setup karna:
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
Home, About, aur Contact components ka example:
function Home() {
return <h1>Home Page</h1>;
}
function About() {
return <h1>About Us</h1>;
}
function Contact() {
return <h1>Contact Us</h1>;
}
React Router DOM mein navigation ke liye <Link>
component ka use karte hain:
import { Link } from 'react-router-dom';
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
}
Dynamic routing ke liye URL parameters ka use karte hain:
<Route path="/user/:id" element={<User />} />
function User() {
const { id } = useParams();
return <h1>User ID: {id}</h1>;
}
Nested routes ko define karne ke liye <Outlet>
ka use karte hain:
<Route path="/dashboard" element={<Dashboard />}>
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet />
</div>
);
}
Agar koi route match nahi karta hai toh 404 page dikhane ke liye:
<Route path="*" element={<NotFound />} />
function NotFound() {
return <h1>404 - Page Not Found</h1>;
}
Programmatically navigate karne ke liye useNavigate
hook ka use karte hain:
import { useNavigate } from 'react-router-dom';
function Login() {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/dashboard')}>
Login
</button>
);
}
React Router DOM ek powerful tool hai jo SPAs mein routing ko handle karta hai. Iska use karke aap dynamic aur interactive web applications bana sakte hain.