Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

React JS Notes

The document provides an overview of React.js, including its components, state management, event handling, and best practices. It also covers setting up a React project, using JSX, React Router, forms, hooks, and performance optimization techniques. Additionally, it outlines a project for creating a movie search app and introduces Redux Toolkit concepts such as store and actions.

Uploaded by

Akash Kale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

React JS Notes

The document provides an overview of React.js, including its components, state management, event handling, and best practices. It also covers setting up a React project, using JSX, React Router, forms, hooks, and performance optimization techniques. Additionally, it outlines a project for creating a movie search app and introduces Redux Toolkit concepts such as store and actions.

Uploaded by

Akash Kale
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

React.

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.

2. Setting Up React Project


To set up a React project, use create-react-app:
npx create-react-app my-app
cd my-app
npm start

3. JSX (JavaScript XML)


JSX allows you to write HTML elements in JavaScript and
place them in the DOM without using functions like
createElement.

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.

10. Handling Side Effects with useEffect


useEffect is used to perform side effects in function
components, such as fetching data or updating the DOM.
11. Conditional Rendering
React allows rendering elements conditionally using if-else
statements or ternary operators.

12. Error Boundaries


Error boundaries are React components that catch JavaScript
errors in child components.

13. Styling in React


Styling can be done using CSS, CSS Modules, or libraries like
styled-components.

14. Performance Optimization


Techniques like memoization, virtualization, and lazy loading
are used to optimize performance.

15. Deployment
React applications can be deployed on platforms like Vercel,
Netlify, or GitHub Pages.

16. Best Practices and Tips


1. Write reusable components.
2. Use keys in lists.
3. Optimize rendering with React.memo.
4. Use PropTypes for type checking.
React.js Notes
1. Introduction to React.js
React.js ek JavaScript library hai jo Facebook ne banayi thi
user interfaces banane ke liye, khaaskar single-page
applications ke liye. Ye developers ko reusable UI
components create karne ki suvidha deti hai.

Activity: Ek simple "Hello World" React component banao jo


screen par text display kare.

function App() {
return <h1>Hello World!</h1>;
}
export default App;

Activity: Ek "Welcome" component banao jo props se name


accept kare aur "Welcome, [name]!" display kare.

2. Setting Up React Project


React project setup karne ke liye create-react-app ka use
karein:

npx create-react-app my-app


cd my-app
npm start
Activity : Apne system par ek React project setup karo aur
"My First React App" ko screen par render karo.

Activity : Ek "About Us" page banao jo ek heading aur


paragraph show kare.

3. JSX (JavaScript XML)


JSX HTML aur JavaScript ko mix karne ki suvidha deta hai, aur
ye DOM mein elements add karna easy banata hai bina
createElement jaise functions ke.

Activity: Ek JSX element banao jo ek paragraph aur ek list


display kare.

const App = () => (


<div>
<p>Welcome to JSX!</p>
<ul>
<li>Point 1</li>
<li>Point 2</li>
</ul>
</div>
);

Activity: ak product component banao jo ek product ka naam


aur price display kare
4. Components
React applications ke components building blocks hote hain.
Ye functional ya class-based ho sakte hain.

Activity: Ek "Header" aur "Footer" component banao aur


unhe main App component mein use karo.

function Header() {
return <header>Header Content</header>;
}
function Footer() {
return <footer>Footer Content</footer>;
}

function App() {
return (
<div>
<Header />
<Footer />
</div>
);
}

Activity: Ek "MainContent" component banao jo ek


paragraph aur ek image display kare.
5. Event Handling
React synthetic events ka use karta hai jo har browser mein
consistent hote hain.

Activity: Ek button banao jo click hone par console par


message print kare.

function App() {
const handleClick = () => {
console.log("Button clicked!");
};

return <button onClick={handleClick}>Click Me</button>;


}

Activity : Ek input field banao jo user input ko state mein


save kare aur real-time display kare.
6. State Management
State ek component ke dynamic data ko represent karta hai.
useState ya Redux ka use karke state manage kar sakte hain.

Activity: Ek counter app banao jo button click par increment


kare.

import { useState } from "react";

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.

Activity: Ek "Home" aur "About" page banao aur unke beech


navigate karo.

import { BrowserRouter as Router, Route, Link } from "react-


router-dom";

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.

Activity: Ek login form banao jisme username aur password


state mein store ho.

function App() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

const handleSubmit = (e) => {


e.preventDefault();
console.log({ username, password });
};

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.

Activity: Ek custom hook banao jo window size ko track kare.

import { useState, useEffect } from "react";

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>;
}

10. Handling Side Effects with useEffect


useEffect side effects jaise data fetch karna ya DOM update
karne ke liye use hota hai.
Activity: Ek app banao jo API se data fetch kare aur display
kare.
import { useState, useEffect } from "react";

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.

Activity: Ek app banao jo login aur logout button condition ke


hisaab se dikhaye.

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.

Activity: Ek error boundary component implement karo.

class ErrorBoundary extends React.Component {


constructor(props) {
super(props);
this.state = { hasError: false };
}

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>
);
}

13. Styling in React


React me styling ke liye CSS, CSS Modules, ya styled-
components ka use karte hain.

Activity: Ek styled component banao jo button ko style kare.

import styled from "styled-components";

const StyledButton = styled.button`


background-color: blue;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
`;

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.

Activity: Ek React.memo component banao jo unnecessary


re-renders ko avoid kare.

import React, { useState, memo } from "react";

const Child = memo(({ value }) => {


console.log("Child rendered");
return <p>{value}</p>;
});

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.

16. Best Practices and Tips


1. Reusable components likho: Baar-baar use hone wale
components banayein.
2. Keys ka use karo: Lists render karte waqt unique keys
dena zaroori hai.
3. React.memo ka use karo: Performance optimization ke
liye.
4. PropTypes ka use karo: Props ka type check karne ke
liye.
Activity: Ek app banao jo PropTypes ka use kare.

import PropTypes from "prop-types";

function Greeting({ name }) {


return <p>Hello, {name}!</p>;
}

Greeting.propTypes = {
name: PropTypes.string.isRequired,
};
function App() {
return <Greeting name="John" />;
}

Movie App project


Outcome:

Ek functional movie search app banega jisme user movie


ka naam enter kar ke uski details dekh sakte hain. Is
activity se aapko API se data fetch karna, user input handle
karna, aur movie data ko display karna seekhne ko milega.

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

movie details ko display karega.


o Search Component: Yeh component user se movie

ka naam lega.
o Movie Info Component: Yeh component movie ke

details (jaise title, rating, release date) ko show


karega.
3. API Integration:
o OMDB (Open Movie Database) ya TMDB (The

Movie Database) API use karenge jisse movie data


fetch kar sake.
4. State Management:
o React state ka use karenge movie data aur error

handling ko manage karne ke liye.


o

5. Styling:
o CSS ka use karke app ko visually appealing bana

sakte ho.

Features:

• User input ke liye search bar.


• API se movie data fetch karna.
• Movie information display karna (title, release date,
rating, description, etc.).
• Error handling agar movie galat naam ho.
Example Code:
import React, { useState } from 'react';
import './App.css';

const App = () => {


const [query, setQuery] = useState(''); // Store the search query
const [movie, setMovie] = useState(null); // Store the fetched movie data
const [error, setError] = useState(''); // Store error message

// Fetch movie data from OMDB API


const fetchMovie = async () => {
try {
// Make API request with the movie title entered by the user
const response = await fetch(`https://www.omdbapi.com/?t=${query}&apikey=8d704d81`);
const data = await response.json();

// Handle the response: if movie not found, display error


if (data.Response === 'False') {
setError('Movie not found');
setMovie(null);
} else {
setMovie(data); // Set movie data to state
setError(''); // Clear error message
}
} catch (err) {
setError('Error fetching data');
}
};

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 */}

{movie && ( // Display movie details if movie is found


<div className="movie-info">
<h2>{movie.Title}</h2>
<p>Release Date: {movie.Released}</p>
<p>Rating: {movie.imdbRating}</p>
<p>{movie.Plot}</p>
<img src={movie.Poster} alt={movie.Title} className="poster" />
</div>
)}
</div>
);
};

export default App;

export default MovieApp;

Redux Toolkit Notes


Store in Redux
• Definition:
Redux mein store wo jagah hoti hai jahan application ki
saari state rakhi jaati hai. Ye centralized state store hai,
jahan se hum data access kar sakte hain, state ko update
kar sakte hain, aur components ko subscribe kar sakte
hain.
• Key Points:
o Store mein humari application ki saari state hoti

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

zarurat hoti hai.


• Example:

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

change karna hai.


o Har action mein ek type hota hai jo action ka type

define karta hai.


o Action Creators wo functions hote hain jo actions

ko create karte hain.


• Example:

javascript
Copy code
const action = {
type: 'ADD_ITEM',
payload: { id: 1, name: 'item 1' }
};

Action Creator Example:


javascript
Copy code
function addItem(item) {
return {
type: 'ADD_ITEM',
payload: item
};
}

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.,

state ko mutate nahi karte, nayi state return karte


hain).
o Default state ko reducer mein initialize kiya jaata

hai.
• Example:
javascript
Copy code
const initialState = { items: [] };

function itemsReducer(state = initialState, action) {


switch(action.type) {
case 'ADD_ITEM':
return { ...state, items: [...state.items,
action.payload] };
default:
return state;
}
}

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

display karna padta hai.


o React-Redux ki madad se hum store ko React

components se connect karte hain.


o useSelector se hum state ko access karte hain aur

useDispatch se actions dispatch karte hain.


• Example:

javascript
Copy code
import { useDispatch, useSelector } from 'react-redux';

const ItemList = () => {


const items = useSelector(state => state.items); //
Access state
const dispatch = useDispatch(); // Dispatch actions

const addItem = (item) => {


dispatch(addItem(item)); // Dispatch an action
};

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.

You might also like