React JS Notes
React JS Notes
js Topics
1. Introduction to React.js
React.js is a JavaScript library developed by Facebook for
building user interfaces, especially single-page applications. It
allows developers to create reusable UI components.
4. Components
Components are the building blocks of a React application.
They can be functional or class-based.
5. Event Handling
React uses synthetic events to handle events consistently
across different browsers.
6. State Management
State represents dynamic data in a component and can be
managed using useState or external libraries like Redux.
7. React Router
React Router is used for navigation between different
components or views in a React application.
8. Forms in React
React allows handling forms with controlled components
where form elements are bound to state.
9. Hooks
Hooks (e.g., useState, useEffect, useContext) allow functional
components to have state and other React features.
15. Deployment
React applications can be deployed on platforms like Vercel,
Netlify, or GitHub Pages.
function App() {
return <h1>Hello World!</h1>;
}
export default App;
function Header() {
return <header>Header Content</header>;
}
function Footer() {
return <footer>Footer Content</footer>;
}
function App() {
return (
<div>
<Header />
<Footer />
</div>
);
}
function App() {
const handleClick = () => {
console.log("Button clicked!");
};
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count +
1)}>Increment</button>
</div>
);
}
Activity: Ek todo app banao jisme user todos add aur remove
kar sake.
7. React Router
React Router ka use navigation ke liye hota hai jo alag-alag
components ya views ke beech hoti hai.
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</nav>
<Route path="/" exact component={() => <h1>Home
Page</h1>} />
<Route path="/about" component={() => <h1>About
Page</h1>} />
</Router>
);
}
8. Forms in React
React forms ko handle karna controlled components ke
saath aasan hota hai jahan form elements state se bind hote
hain.
function App() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
);
}
9. Hooks
React ke hooks (jaise useState, useEffect, useContext)
functional components ko state aur features dene ki suvidha
dete hain.
function useWindowSize() {
const [size, setSize] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setSize(window.innerWidth);
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize",
handleResize);
}, []);
return size;
}
function App() {
const size = useWindowSize();
return <p>Window size: {size}px</p>;
}
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return (
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
}
11. Conditional Rendering
React me condition ke hisaab se elements render kar sakte
hain using if-else ya ternary operators.
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? (
<button onClick={() =>
setIsLoggedIn(false)}>Logout</button>
):(
<button onClick={() =>
setIsLoggedIn(true)}>Login</button>
)}
</div>
);
}
12. Error Boundaries
Error boundaries React components hote hain jo child
components me error ko pakadte hain aur UI ko crash hone
se bachate hain.
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
function App() {
return (
<ErrorBoundary>
<h1>My App</h1>
</ErrorBoundary>
);
}
function App() {
return <StyledButton>Click Me</StyledButton>;
}
14. Performance Optimization
React apps ke performance ke liye memoization,
virtualization, aur lazy loading techniques ka use hota hai.
function App() {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
return (
<div>
<Child value={text} />
<button onClick={() => setCount(count + 1)}>Increment
Count</button>
<input onChange={(e) => setText(e.target.value)} />
</div>
);
}
15. Deployment
React apps ko Vercel, Netlify, ya GitHub Pages par deploy kar
sakte hain.
Activity: Apne React app ko Vercel par deploy karo aur live
URL generate karo.
Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
function App() {
return <Greeting name="John" />;
}
Steps:
1. Project Setup:
o Create a new React app using npx create-react-app
movie-search-app.
2. Movie App Structure:
o App Component: Yeh main component hoga jo
ka naam lega.
o Movie Info Component: Yeh component movie ke
5. Styling:
o CSS ka use karke app ko visually appealing bana
sakte ho.
Features:
return (
<div className="app-container">
<h1 className="header">Movie Search App</h1>
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)} // Update query as the user types
className="input"
placeholder="Search for a movie"
/>
<button onClick={fetchMovie} className="button">Search Movie</button>
{error && <p className="error">{error}</p>} {/* Display error message if any */}
hai.
o Store ko update karne ke liye actions dispatch
karte hain.
o Redux mein ek application mein sirf ek store hota
hai.
o Store ko update karne ke liye ek reducer function ki
javascript
Copy code
const store = createStore(reducer);
Actions in Redux
• Definition:
Actions Redux mein plain JavaScript objects hoti hain jo
kisi event ko describe karti hain, jise hum state mein
change karna chahte hain. Actions mein ek type hota hai
aur ek optional payload hota hai jo additional data ho
sakta hai.
• Key Points:
o Actions hi reducers ko batate hain ki state ko kaise
javascript
Copy code
const action = {
type: 'ADD_ITEM',
payload: { id: 1, name: 'item 1' }
};
Reducers in Redux
• Definition:
Reducers wo functions hote hain jo decide karte hain ki
state kaise change hogi jab koi action dispatch hota hai.
Ye purani state aur action ko input ke roop mein lete
hain aur nayi state return karte hain.
• Key Points:
o Reducers ko current state aur action dono pass kiye
jaate hain.
o Reducers ko pure functions hona chahiye (i.e.,
hai.
• Example:
javascript
Copy code
const initialState = { items: [] };
Dispatch in Redux
• Definition:
Dispatch ek method hai jo actions ko store tak bhejta
hai. Ye actions ko process karne ke liye reducers ko
trigger karta hai.
• Key Points:
o Aap dispatch function se actions ko store mein
bhejte hain.
o Dispatch ke baad store ka state update ho jaata
hai.
• Example:
javascript
Copy code
store.dispatch({
type: 'ADD_ITEM',
payload: { id: 2, name: 'item 2' }
});
View in Redux
• Definition:
View se mera matlab hai wo React components jo state
ko render karte hain aur user input ko handle karte hain.
Redux mein view wo components hain jo state ko
display karte hain.
• Key Points:
o View ko store se state ko subscribe karke state ko
javascript
Copy code
import { useDispatch, useSelector } from 'react-redux';
return (
<div>
<ul>
{items.map(item => <li
key={item.id}>{item.name}</li>)}
</ul>
<button onClick={() => addItem({ id: 3, name: 'item 3'
})}>Add Item</button>
</div>
);
};
Redux Flow
1. User Interaction: User UI ke saath interact karta hai
(button click, input fields, etc.).
2. Dispatch Action: Jab user koi interaction karta hai, ek
action dispatch hota hai.
3. Reducer Update State: Action ke basis pe reducer state
ko update karta hai.
4. View Renders: Updated state ke saath view component
re-render hota hai.