0% found this document useful (0 votes)
5 views40 pages

Front-End Freamework

The document provides an overview of three popular JavaScript frameworks: Vue.js, Angular, and ReactJS, highlighting their features and functionalities. Vue.js is known for its ease of learning and reactivity, Angular for its component-based architecture and two-way data binding, and ReactJS for its component-based structure and performance through Virtual DOM. Additionally, it includes practical examples of React components, JSX syntax, and how to set up a React environment.

Uploaded by

rata.divya2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views40 pages

Front-End Freamework

The document provides an overview of three popular JavaScript frameworks: Vue.js, Angular, and ReactJS, highlighting their features and functionalities. Vue.js is known for its ease of learning and reactivity, Angular for its component-based architecture and two-way data binding, and ReactJS for its component-based structure and performance through Virtual DOM. Additionally, it includes practical examples of React components, JSX syntax, and how to set up a React environment.

Uploaded by

rata.divya2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

 Introduction to vue.

js:
Vue.js is a tool that helps you build websites that change and update without
reloading the page. For example: When you type in a form and the text
shows up right away, or when you click a button and something happens—
Vue.js helps make that easy.

 Feature of VueJS:
1) Easy to Learn - Vue.js is beginner-friendly. You can start using it just by
linking a script in your HTML file—no complex setup needed. Its syntax is
simple and close to plain HTML and JavaScript, which makes it easier to pick
up compared to other frameworks.

2) Reactivity - Vue has a built-in reactivity system. This means when your data
changes, the webpage updates automatically to show the new values. You
don’t need to write extra code to refresh or reload parts of the page—it just
works.

3) Components - Vue lets you break your UI into small, reusable pieces called
components. Each component has its own code and styling, which makes
your app cleaner, more organized, and easier to maintain. For example: a
button or a form can be a component.
4) Directives - Vue uses special HTML-like commands called directives. These
start with v-, like v-if for showing something only if a condition is true, or v-
for for looping through items. They make it simple to control the behavior of
the page directly from the HTML.

5) Single File Components - With Vue, you can write the HTML, JavaScript, and
CSS for each component in a single .vue file. This keeps everything related to
that part of your app in one place, making your code easier to read and
maintain.

6) Composition API - The Composition API is a new way to write Vue code,
introduced in Vue 3. It gives you more flexibility and helps organize logic
better, especially in large or complex apps. It’s great for reusing code
between components.
• Introduction to Angular:
Angular is a platform and framework for building powerful web applications. It
helps you create websites where parts of the page update instantly when users
interact with them. For example: when you submit a form, click a tab, or filter
search results—Angular handles all that smoothly without needing to reload the
whole page.

• Features of Angular:
1) Component-Based Architecture – Angular apps are made using components.
Each component controls a part of the screen, and you can reuse them
across the app. This helps organize your code and makes your app more
manageable.
2) Two-Way Data Binding – Angular connects your data and your user
interface. When data changes in the code, the screen updates. And when a
user changes something on the screen, the data in your code updates too—
automatically.
3) Built-in Directives – Angular provides helpful tools in HTML called directives.
These let you add behavior like showing/hiding elements (*ngIf) or repeating
lists (*ngFor) without writing extra JavaScript.
4) Dependency Injection – Angular has a system that helps your app get the
resources it needs, like services or data, without manually managing them.
This makes your code cleaner, more flexible, and easier to test.
5) Routing – Angular includes a router that lets you build single-page
applications (SPAs) where you can move between pages without a full
reload. It also supports features like lazy loading for better performance.
6) TypeScript Support – Angular is built using TypeScript, a typed version of
JavaScript. This makes it easier to find errors, understand your code, and
write large applications that are easier to manage.
 Frontend Framework:
Introduction to ReactJS:
ReactJS is a free and open-source front-end JavaScript library which is used to
develop various interactive user-interfaces. It is a simple, feature rich and
component based UI library.
When we say component based, we mean that React develops applications
by creating various reusable and independent codes. ReactJS can be used to
develop small applications as well as big, complex applications.

 Feature of ReactJS:
1) Component Based − ReactJS makes use of multiple components to build
an application. These components are independent and have their own
logic which makes them reusable throughout the development process.
This will drastically reduce the application's development time.
2) Better and Faster Performance − ReactJS uses Virtual DOM. Virtual DOM
compares the previous states of components of an application with the
current states and only updates the changes in Real DOM. Whereas,
conventional web applications update all components again. This helps
ReactJS in creating web applications faster.
3) Extremely Flexible − React allows developers and teams to set their own
conventions that they deem are best suited and implement it however
they see fit, as there are no strict rules for code conventions in React.
4) Creates dynamic applications easily − Dynamic web applications require
less coding while offering more functionality. Thus, ReactJS can create
them easily.
5) Develops Mobile Applications as well − Not only web applications, React
can also develop mobile applications using React Native. React Native is
an open-source UI software framework that is derived from React itself. It
uses React Framework to develop applications for Android, macOS, Web,
Windows etc.
6) Debugging is Easy − The data flow in React is unidirectional, i.e., while
designing an app using React, child components are nested within parent
components. As the data flows is in a single direction, it gets easier to
debug errors and spot the bugs.

 How does React work?


React operates by creating an in-memory virtual DOM rather than directly
manipulating the browser’s DOM. It performs necessary manipulations
within this virtual representation before applying changes to the actual
browser DOM.

1) Virtual DOM is like a copy of the real webpage - React creates a


lightweight version of the webpage (Virtual DOM) using JavaScript
objects. This copy is faster to work with than the actual webpage.
2) When something changes (like a button click) - React creates a new
version of the Virtual DOM with the updated content. It compares the
new version with the old version to see what changed (this is called
"diffing").
3) React updates only the changed parts - Instead of rebuilding the whole
webpage, React updates only the part that changed. This makes it fast
because React avoids doing extra work.
 React Environment Setup:
Step 1: Navigate to the folder where you want to create the project and
open it in terminal

Step 2: In the terminal of the application directory type the following


command

npx create-react-app <<Application_Name>>

Step 3: Navigate to the newly created folder using the command

cd <<Application_Name>>

Step 4: A default application will be created with the following project


structure and dependencie. It will install some packages by default which
can be seen in the dependencies in package.json.

Step 5: To run this application type the following command in terminal

npm start

Step 6: The following output will be displayed in the browser

ReactJS Installation

You can modify the application according to your preferences and change
the code accordingly.
App.js:

import './App.css';
function App() {
const pstyle = {
backgroundColor: 'purple',
fontSize: '20px',
color: 'yellow',
textAlign:'left',
};

return (
<div className="App">
<h1 className="text-center">Hello World</h1>
<p style={pstyle}>Lorem ipsum dolor sit amet consectetur adipisicing elit.
Quae praesentium sunt veritatis harum illo. Facere cupiditate saepe asperiores
illum earum?</p>
</div>
);
}
export default App;

Index.js:

import React from 'react';


import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

reportWebVitals();
 Map() method:
map() method in React is used to loop through an array and create a new
array of elements. In React, you use map() to generate lists of
components or HTML elements dynamically. React needs a unique key for
each item to track changes efficiently.

map_method.js:
import React from 'react';

export const MapMethod = () => {


const myArray = ['apple', 'banana', 'orange'];

const myList = myArray.map((item) => <p key={item}>{item}</p>);

return (
<div>
<h2>My Fruits:</h2>
{myList}
</div>
);
};

App.js:
import './App.css';
import {HelloWorld} from "./MyComponent/hello-world";
import {MapMethod} from "./MyComponent/map_method";

function App() {
return (
<div className="App">
<h1 className="text-center">Hello World</h1>
{HelloWorld()}
{MapMethod()}
<hello/>
</div>
);
}
export default App;
 React Render HTML:
React's goal is in many ways to render HTML in a web page. React
renders HTML to the web page by using a function called createRoot()
and its method render().

1) The createRoot Function - The createRoot() function takes one


argument, an HTML element. The purpose of the function is to define
the HTML element where a React component should be displayed.
2) The render Method - The render() method is then called to define the
React component that should be rendered. There is another folder in
the root directory of your React project, named "public". In this folder,
there is an index.html file. There is a single <div> in the body of this file.
This is where our React application will be rendered.

App.js:
import './App.css';
function App() {
return (
<div className="App">
<h1 className="text-center">Hello World</h1>
</div>
);
}
export default App;

index.html:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>

</body>
 JSX (JavaScript XML):
JSX (JavaScript XML) is a feature in React that allows you to write HTML-
like code directly within JavaScript. It makes it easier to create and
structure components by combining HTML and JavaScript in one place.
Instead of using complex JavaScript code to create elements, you can
write them in a format that looks like HTML, and React will convert it into
JavaScript behind the scenes.

1) Expressions in JSX - With JSX you can write expressions inside curly
braces { }. The expression can be a React variable, or property, or any
other valid JavaScript expression. JSX will execute the expression and
return the result:

const myElement = <h1>React is {5 + 5} times better with JSX</h1>;

2) Inserting a Large Block of HTML - To write HTML on multiple lines, put


the HTML inside parentheses:

const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(myElement);
3) One Top Level Element - The HTML code must be wrapped in ONE top
level element. So if you like to write two paragraphs, you must put
them inside a parent element, like a div element.

const myElement = (
<div>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</div>
);

Alternatively, you can use a "fragment" to wrap multiple lines. This will
prevent unnecessarily adding extra nodes to the DOM. A fragment
looks like an empty HTML tag: <></>.
4) Elements Must be Closed - JSX follows XML rules, and therefore HTML
elements must be properly closed.

const myElement = <input type="text" />;

5) Attributes in JSX - JSX supports HTML like attributes. All HTML tags and
its attributes are supported. Attributes has to be specified using
camelCase convention (and it follows JavaScript DOM API) instead of
normal HTML attribute name. For example, class attribute in HTML has
to be defined as className. The following are few other examples:

a) htmlFor instead of for


b) tabIndex instead of tabindex
c) onClick instead of onclick

import React from 'react';


import ReactDOM from 'react-dom/client';

const myElement = <h1 className="myclass">Hello World</h1>;

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(myElement);
 React Components:

Components are independent and reusable bits of code. They serve the
same purpose as JavaScript functions, but work in isolation and return
HTML. Components come in two types, Class components and Function
components, in this tutorial we will concentrate on Function components.
1) Class Component - A class component must include the extends
React.Component statement. This statement creates an inheritance to
React.Component, and gives your component access to
React.Component's functions. The component also requires a render()
method, this method returns HTML.

class Car extends React.Component {


render() {
return <h2>Hi, I am a Car!</h2>;
}
}

2) Function Component - Here is the same example as above, but created


using a Function component instead. A Function component also
returns HTML, and behaves much the same way as a Class component,
but Function components can be written using much less code, are
easier to understand, and will be preferred in this tutorial.

function Bike() {
return <h2>Hi, I am a Bike!</h2>;
}

3) Rendering a Component - Now your React application has a


component called Car, which returns an <h2> element. To use this
component in your application, use similar syntax as normal HTML:
<Car />

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Car />);
4) Props - Components can be passed as props, which stands for
properties. Props are like function arguments, and you send them into
the component as attributes.

function Cycle(props) {
return <h2>I am a {props.color} Cycle!</h2>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Car color="red"/>);

5) Components in Components - We can refer to components inside


other components:

function Airplane() {
return <h2>I am a Airplane and I live in Garage!</h2>;
}

function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Airplane />
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Garage />);

6) Components in Files - React is all about re-using code, and it is


recommended to split your components into separate files. To do that,
create a new file with a .js file extension and put the code inside it:
Cycle.js:
export function Cycle(props) {
return <h2>I am a {props.color} Cycle!</h2>;
}
App.js:
import './App.css';
import {Cycle} from "./MyComponent/component";
function App() {
return (

<div>

<Cycle color='Blue'/>

</div>
);
}
export default App;

 Props Component:
Props are arguments passed into React components. Props are passed to
components via HTML attributes. props stands for properties. React
Props are like function arguments in JavaScript and attributes in HTML. To
send props into a component, use the same syntax as HTML attributes:

Cycle.js:
export function Cycle(props) {
return <h2>I am a {props.color} Cycle!</h2>;
}

App.js:
import './App.css';
import {Cycle} from "./MyComponent/component";
function App() {
return (

<div>

<Cycle color='Blue'/>

</div>
);
}
export default App;
 Pass Data Using Props:

1) Using Variable - If you have a variable to send, and not a string as in the
example above, you just put the variable name inside curly brackets:

function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}

function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}

2) Using Object:

function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}

function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
 Prop Validation:
React community provides a special package, prop-types to address the
properties type mismatch problem. prop-types allows the properties of the
component to be specified with type through a custom setting (propTypes)
inside the component.

PropType Description Example


PropTypes.string A string name: PropTypes.string
PropTypes.number A number age: PropTypes.number
A boolean
PropTypes.bool isActive: PropTypes.bool
value
PropTypes.func A function onClick: PropTypes.func
PropTypes.array An array items: PropTypes.array
PropTypes.object An object data: PropTypes.object
Anything
that can be
rendered
PropTypes.node (string, children: PropTypes.node
number,
element,
etc.)
A React
PropTypes.element component: PropTypes.element
element
One of a
size: PropTypes.oneOf(['small',
PropTypes.oneOf([]) specific set
'medium', 'large'])
of values
One of value:
PropTypes.oneOfType([]) several PropTypes.oneOfType([PropTypes.string,
types PropTypes.number])
Array of
items:
PropTypes.arrayOf() specific
PropTypes.arrayOf(PropTypes.string)
type
Object with
values of data:
PropTypes.objectOf()
specific PropTypes.objectOf(PropTypes.number)
type
PropTypes.any Any value value: PropTypes.any
App.js:
import React from 'react';
import PropTypes from 'prop-types';

export const UserAge = ({ age }) => {


return <div>User age: {age}</div>;
};

UserAge.propTypes = {
age: PropTypes.number.isRequired, // Ensures 'age' is a required number prop
};
 ReactJS Styling:
There are different ways to apply css in ReactJS in which most
commonly used are follows:
1) Inline Styling - Inline Styling is one of the safest ways to style the React
component. It declares all the styles as JavaScript objects using DOM
based css properties and set it to the component through style attributes.
Since the inline CSS is written in a JavaScript object, properties with
hyphen separators, like background-color, must be written with camel
case syntax:

App.js:
import './App.css';
function App() {

return (
<div className="App">
<h1 className="text-center">Hello World</h1>
<p style={{ color: 'yellow', backgroundColor: 'purple'}}>Lorem ipsum dolor
sit amet consectetur adipisicing elit.
</p>
</div>
);
}
export default App;

2) JavaScript Object - You can also create an object with styling information,
and refer to it in the style attribute:

App.js:
import './App.css';
function App() {
const pstyle = {
backgroundColor: 'purple',
fontSize: '20px',
color: 'yellow',
};

return (
<div className="App">
<h1 style={pstyle}Hello World</h1>
</div>
);
}
export default App;

3) CSS Modules - Css Modules provides safest as well as easiest way to


define the style. It uses normal css stylesheet with normal syntax. While
importing the styles, CSS modules converts all the styles into locally
scoped styles so that the name conflicts will not happen. Let us change
our component to use CSS modules
 Conditional Statement:
1) if Statement - The if statement allows you to choose which component
to show based on a condition. If the condition is true, one component is
rendered; if false, another component is shown. This is useful when you
need more complex logic before deciding what to display.

2) && Operator - The && operator shows a component only if the


condition is true. If the condition is false, nothing is displayed. This is
helpful for simple cases where you only need to display content when a
condition is met.

3) Ternary Operator (? :) - The ternary operator allows you to choose


between two components based on a condition. If the condition is true,
it shows the first component; if false, it shows the second component.
It’s useful for quick "if-else" situations inside JSX.
 React Lists:
In React, a list is a collection of items (like an array) that can be rendered
dynamically using JavaScript loops. Lists are commonly used to display data
sets, such as an array of objects or strings, in a structured format like a list
or table.

1) map() Method - The map() method creates a new array by applying a


function to each element in the original array. In React, map() is often
used to generate a list of components because it allows you to write clean
and concise code.

2) for Loop - You can use a for loop to create lists in React by manually
pushing elements into an array and then returning that array in JSX. This
approach is useful when you need more control over the loop execution.

3) while Loop - A while loop can also be used to generate lists, but it is less
common. Similar to the for loop, you need to push elements into an array
and return the array in JSX.

List.js:
import React from 'react';

function Car(props) {
return <li>I am a {props.brand}</li>;
}

export function CarList() {


const cars = ['Ford', 'BMW', 'Audi'];
const carList1 = [];
const carList2 = [];
let j = 0;

for (let i = 0; i < cars.length; i++) {


carList1.push(<Car key={i} brand={cars[i]} />);
}

while (j < cars.length) {


carList2.push(<Car key={j} brand={cars[j]} />);
j++;
}
return (
<>
<h1>Who lives in my garage? (example usin map) </h1>
<ul> {cars.map((car, index) => <Car key={index} brand={car} />)}</ul>
<h1>Who lives in my garage? (example using for loop) </h1>
<ul>{carList1}</ul>

<h1>Who lives in my garage? (example using while loop) </h1>


<ul>{carList2}</ul>
</>
);
}

 Keys:
Keys help React identify which elements have changed, been added, or
removed. Each key should be unique among siblings to allow React to
efficiently update and render the list without re-rendering unchanged
elements.

EXAMPLE:

function Garage() {
const cars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car key={car.id} brand={car.brand} />)}
</ul>
</>
);
}
 State in ReactJS:
State in ReactJS is an object that holds a component's dynamic data and
controls how the component behaves. When the state changes, React
automatically updates and re-renders the component to show the latest
data. This helps create interactive user interfaces that respond to user
actions.
a) Creating State Object - Creating a state is essential to building dynamic
and interactive components. We can create a state object within the
constructor of the class component.
b) Updating State in React - In React, a State object can be updated using
setState() method. React may update multiple setState() updates in a
single go. Thus using the value of the current state may not always
generate the desired result.
c) Managing Complex State - In React class components, state can be more
than just primitive values like numbers or strings. You can manage
complex state objects or arrays, but you need to be careful when
updating them to avoid directly mutating the state
Syntax:
this.state = { objectName: { property1: value1, property2: value2 } };
this.setState((prevState) => ({ objectName: { ...prevState.objectName,
updatedProperty: newValue } }));

initialize state as an object in the constructor, then use setState() to


update the object, preserving previous values with the spread operator
EXAMPLE:
import React from "react";

export class StateComponent extends React.Component {


//create state
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
//change state
increment = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
//change state
decrement = () => {
this.setState((prevState) => ({
count: prevState.count - 1,
}));
};

render() {
return (
<div>
<h1>
The current count is :{" "}
{this.state.count}
</h1>
<button onClick={this.increment}>
Increase
</button>
<button onClick={this.decrement}>
Decrease
</button>
</div>
);
}
}
 Event in ReactJS:

Events are just some actions performed by a user to interact with any
application. They can be the smallest of actions, like hovering a mouse
pointer on an element that triggers a drop-down menu, resizing an
application window, or dragging and dropping elements to upload them etc.
Events in React are divided into three categories:
a) Mouse Events − onClick, onDrag, onDoubleClick
b) Keyboard Events − onKeyDown, onKeyPress, onKeyUp
c) Focus Events − onFocus, onBlur

 Event Management:
1) Adding Events in React - In React, events are written in camelCase
format. For example, instead of onclick used in HTML, React uses onClick.
Event handlers in React are written inside curly braces {}.
Example Comparison:
In React: <button onClick={shoot}>Take the Shot!</button>
In HTML: <button onclick="shoot()">Take the Shot!</button>

export function Football() {


const shoot = () => {
alert("Great Shot!");
}

return (
<button onClick={shoot}>Take the shot!</button>
);
}
2) Passing Arguments to Event Handlers - To pass an argument to an event
handler, you can use an arrow function. This allows you to pass data or
values directly to the event handler.

export function Cricket() {


const shoot = (a) => {
alert(a);
}

return (
<button onClick={() => shoot("Six!")}>Take the shot!</button>
);
}

3) React Event Object - The React Event Object is a special object that React
creates when an event (like a click) happens. It wraps the native browser
event and gives it a consistent structure across all browsers. It helps React
work the same way on different browsers. It gives you extra information
about the event, like:
a) event.target – The element that triggered the event.
b) event.type – The type of event (e.g., "click").
c) event.preventDefault() – Stops the default action (like stopping a
form from submitting).
d) event.persist() - If you want to use the event data after the handler
finishes(like a setTimeout), you need to store it using
event.persist().

export function Win() {


const shoot = (event) => {
alert(event.type);

setTimeout(() => {
alert("Hurray, Won The Match! 🎉"); // `null` (because of pooling)
}, 3000);

event.persist();
}

return (
<button onClick={(event) => shoot(event)}>Take the shot!</button>
);
}
 React Forms:
React forms allow users to interact with the webpage, similar to how forms
work in HTML. You can create forms in React using the <form> element,
<input> fields, <textarea>, <select>, and other form components.

1) Adding Forms in React - Forms in React are added like any other HTML
element. However, in React, forms are usually controlled by the state
rather than letting the browser handle the data. This gives more control
over user input and how the form behaves.
2) Handling Forms - In HTML, the DOM usually handles form data directly.
However, in React, form data is managed through the component’s state.
This allows you to control the data and update the state in response to
user input using the onChange event handler.
3) Using useState to Manage Form State - React's useState hook is used to
manage form data. When an input changes, you can update the state
using setState or setName. This creates a "single source of truth" where
the input value reflects the state value.
4) Submitting Forms - You can prevent the default form submission (which
reloads the page) using event.preventDefault() inside an onSubmit
handler. This allows you to handle the form submission manually, such as
validating the data or sending it to a server.
5) Handling Multiple Input Fields - To handle multiple inputs in one state
object, you can use the name attribute to identify the input field. You can
then update the state dynamically using [event.target.name] to set the
value of the corresponding field in the state object.
EXAMPLE:
import React, { useState } from 'react';
import './Component.css';

export const FormState = () => {


const [formData, setFormData] = useState({
name: '',
amount: '',
date: '',
category: ''
});
// Handle input changes
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};

// Handle form submission


const handleSubmit = (e) => {
e.preventDefault();

// Simple validation
if (!formData.name || !formData.amount || !formData.date ||
!formData.category) {
alert('Please fill out all fields!');
return;
}

console.log('Form Data Submitted:', formData);

// Clear form after submission

};

return (
<div id="expenseForm">
<form onSubmit={handleSubmit}>
<label htmlFor="name">Title</label>
<input
type="text"
id="name"
name="name"
placeholder="Enter expense title"
value={formData.name}
onChange={handleChange}
/>

<label htmlFor="amount">Amount</label>
<input
type="number"
id="amount"
name="amount"
placeholder="Enter expense amount"
value={formData.amount}
onChange={handleChange}
/>

<label htmlFor="date">Spend Date</label>


<input
type="date"
id="date"
name="date"
value={formData.date}
onChange={handleChange}
/>
<label htmlFor="category">Category</label>
<select
id="category"
name="category"
value={formData.category}
onChange={handleChange}
>
<option value="">Select</option>
<option value="Food">Food</option>
<option value="Entertainment">Entertainment</option>
<option value="Academic">Academic</option>
</select>

<input type="submit" value="Submit" />


</form>
</div>
);
};

 React Animation:

https://www.tutorialspoint.com/reactjs/reactjs_animation.htm
 React Router in Web Applications:

Routing in web applications refers to binding a web URL to a specific


resource or component within the application. In React, routing allows you
to map URLs to components, enabling dynamic navigation between
different views.

 Installing React Router - To set up routing in a React project, you need to


install the react-router-dom package using npm:

cd /path/to/your/project npm install react-router-dom

 React Router Components:

1) Router - The Router component is the foundation of React Router. It


wraps the entire application and provides the routing context, enabling
route management and navigation. It allows the use of history-based
navigation and route matching. Common types include BrowserRouter
(which uses the browser’s history API) and HashRouter (which uses the
hash portion of the URL).
2) Link - The Link component is used to create navigation links in a React
app. It works like an HTML <a> tag but prevents a full-page reload by
using React Router’s internal navigation system. This enables faster and
smoother client-side navigation while maintaining the application state.
3) Route - The Route component is responsible for rendering a specific
component when the URL matches a defined path. It supports static
and dynamic paths (e.g., /product/:id) and can be nested to create
more complex routing structures.
4) Outlet - The Outlet component is used to render child routes within a
parent route. It acts as a placeholder where the matching child
component is displayed. This makes it easy to create nested routes and
maintain consistent layout structures.
 Hook in React:
A hook in React is a special function that lets you use state and lifecycle
features in functional components without needing a class
component.We use hooks to make React code simpler and easier to
manage. They let us add features like saving data (state) and running
code at certain times (like when the page loads) without using complex
class components.

1) UseState hook - The useState hook in React lets you create and
manage data (state) in a function component. It allows your
component to remember values (like user input or a counter) and
update them when needed.
We use useState because it makes it easy to update the component
automatically when the state changes, without needing complex class
components.

a) initialValue - Initial value of the state. state can be specified in any


type (number, string, array and object).
b) state - Variable to represent the value of the state.
c) setState - Function variable to represent the function to update the
state returned by the useState.
EXAMPLE:
import React, { useState } from 'react';

export function UseStateCounter() {


const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Dicrement</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);}
2) useEffect hook - The useEffect hook in React lets you run code
at specific times, like when the component loads, updates, or
gets removed. We use useEffect to handle side effects, such as
fetching data, updating the DOM, or setting up timers, without
needing lifecycle methods from class components.

a) Update function - Update function is the function to be


executed after each render phase. This corresponds to
componentDidMount and componentDidUpdate events
b) Dependency - Dependency is an array with all the variables on
which the function is dependent. Specifying the dependency is
very important to optimize the effect hook.

1. Run Code After Initial Render (ComponentDidMount) - Runs


once after the component renders for the first time when the
dependency array [] is empty.

useEffect(() => {
alert('Component mounted');
}, []); // Empty array = Runs only once (on mount)

2. Run Code After State or Props Change


(ComponentDidUpdate) - Runs every time the specified state
or prop in the dependency array changes.

export function UseEffectCounter() {


const [count, setCount] = useState(0);
useEffect(() => {
alert(`Count changed to: ${count}`);
}, [count]); // Runs whenever 'count' changes
3. Cleanup on Unmount (ComponentWillUnmount) - Returns a
cleanup function that runs when the component unmounts,
useful for clearing intervals, unsubscribing from events, etc.

useEffect(() => {
const timer = setInterval(() => {
console.log('Running every second');
}, 1000);

// Cleanup when component unmounts


return () => clearInterval(timer);
}, []);

3) useRef - The useRef hook in React lets you create a reference to a


DOM element or store a value that doesn’t trigger a re-render when
it changes. We use useRef to access or modify a DOM element
directly (like focusing an input) or to keep a value that persists
between renders without causing updates.

a) val is the initial value to be set for the returned mutable object,
refObj.
b) refObj is the object returned by the hook.

Modify DOM element directly:


//useRef
export function UseRefAccesssChangeColor() {
const inputRef = useRef(null);

const handleFocus = () => {


inputRef.current.style.backgroundColor ='red'; // Access the input and
change color
};

return (
<div>
<br /><br /><input ref={inputRef} type="text" placeholder="Type
something..." />
<br /><br /><br /><button onClick={handleFocus}>Change Color</button>
</div>
);
}
Store value that does not change on re-render:
export function UseRefRerenderWithoutResetValue() {
const a = useRef(0);
const [count, setCount] = useState(0);

const handleClick = () => {


a.current = a.current + 1;
console.log(`Value of a is = ${a.current}`); // Updates without causing
re-render
setCount(count + 1); // Triggers a re-render
};

return (
<div>
<p>State Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}

4) useContext - The useContext hook in React lets you access data (like
a theme or user info) from a central place without passing it down
through props. We use useContext to make it easier to share data
between components, avoiding "prop drilling" (passing props through
many layers).

Parent.jsx:
import React, { createContext } from 'react';
import { ChildA } from './Child_A'; // Import named export

// Create Contexts
const data = createContext();
const data1 = createContext();

export function UseContextParent() {


const name = "Yoshita";
const gender = "Female";

return (
<data.Provider value={name}>
<data1.Provider value={gender}>
<ChildA />
</data1.Provider>
</data.Provider>
);
}

export { data, data1 }; // Export contexts properly


Child_C.jsx:
import React, { useContext } from 'react';
import { data, data1 } from './Parent'; // Fix context import

export function ChildC() {


const FirstName = useContext(data);
const gender = useContext(data1);

return (
<>
<h1>Hi my name is {FirstName} and my gender is {gender}</h1>
</>
);
}

Child_A.jsx:
import React from "react";
import { ChildB } from "./Child_B"; // Importing named export

function ChildA() {
return <ChildB />;
}

export { ChildA }; // Exporting as a named export

Child_B.jsx:
import React from "react";
import { ChildC } from "./Child_C"; // Importing named export

export function ChildB() {


return <ChildC />;
}
5) Custom Hook - A custom hook is a reusable function in React that starts
with use and lets you share stateful logic between components. It helps
reduce code duplication, keeps code cleaner, and makes logic easier to
manage and reuse.

CustomeHook.jsx:
import React from 'react';
import {useCounter} from './CustomCounter';

export function Counter() {


const { count, increment, decrement, reset } = useCounter();

return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}

CustomeCounter.jsx:
import { useState } from 'react';

export function useCounter(initialValue = 0) {


const [count, setCount] = useState(initialValue);

const increment = () => setCount(count + 1);


const decrement = () => setCount(count - 1);
const reset = () => setCount(0);

return { count, increment, decrement, reset };


}
State Management Using Redux:
Redux is a state management library that helps you manage the state (data)
of your application in a single place, making it easier to track and update.
Instead of passing data between components manually, Redux stores all the
state in one central store. When you want to update the state, you send an
action (a description of what should change), and a reducer (a function)
decides how to update the state based on that action. This makes state
changes predictable and easier to debug, especially in large applications.
Index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import {store} from './Store';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<Provider store={store}>
<App />
</Provider>
);

App.js
import './App.css'
import Navbar from './Components/Navbar'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment, multiply } from './Counter/counterSlice'

function App() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()

return (
<>
<Navbar />
<div>
<button onClick={() => dispatch(decrement())}>-</button>
Currently count is {count}
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(multiply())}>*</button>
</div>

</>
)
}

export default App


Store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './Counter/counterSlice';

export const store = configureStore({


reducer: {
counter: counterReducer,
},
})

navBar.js
import React from 'react'
import { useSelector} from 'react-redux'

const Navbar = () => {


const count = useSelector((state) => state.counter.value)

return (
<div>
I am a navbar and counter is {count}
</div>
)
}

export default Navbar

counterSlice.jsx
import { createSlice } from '@reduxjs/toolkit'

const initialState = {
value: 0,
}

export const counterSlice = createSlice({


name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
multiply: (state)=>{
state.value *=2
}
},
})

// Action creators are generated for each case reducer function


export const { increment, decrement, multiply } = counterSlice.actions

export default counterSlice.reducer

You might also like