ReactJS
Introduction :
What is ReactJS?
1. ReactJS is a JavaScript library used to build UI.
2. Its main focus is on UI.
3. It follows component based architecture like header, footer, main content, side nav.
4. DOM updates are handle gracefully in react
5. Component based manage their own state then compose them to make complex UIs.
6. use ES6 - ES6, also known as ECMAScript 2015. ES6 is a major update to JavaScript that includes new syntax and features aimed at making the language more powerful and easier to use.
history :
Initial Release to the Public (V0.3.0) was in July 2013.
Created and Maintained by facebook.
Facebook Software Engineer, Jordan Walke, created it.
What we need :
- Variables and Scope: Understanding how variables are declared (using
var
,let
,const
) and their scope (global vs. function vs. block scope).
Data Types: Familiarity with primitive data types (like
string
,number
,boolean
,null
,undefined
) and complex data types (such asobject
,array
,function
).Functions: Knowing how to define functions, use arrow functions, and understand function scope and closures.
Arrays and Objects: Manipulating arrays (
map
,filter
,reduce
) and working with objects (object literals, destructuring, spreading).ES6+ Features: Being comfortable with modern JavaScript features like arrow functions, template literals, destructuring, spread/rest operators, and
let
/const
for variable declarations.DOM Manipulation: Basic knowledge of how the Document Object Model (DOM) works and how JavaScript interacts with HTML elements.
Event Handling: Understanding how to handle events in JavaScript and React (
onClick
,onChange
, etc.).Modules and Imports: Familiarity with ES6 modules (
import
/export
) and how to organize and reuse code effectively.
React Basics: While not strictly JavaScript, having a conceptual understanding of what React is (a JavaScript library for building user interfaces) and its core principles (like components, JSX, state, and props) will be very helpful.
React Setup :
Node.js
You can download it from: https://nodejs.org/en/
1. using vite
npm create vite@latest my-app --template react
2. using npm
npm install -g create-react-app appName;
Creating our first react app
Run this command to create a React application named my-react-app:
OR, you can directly make your application without specifying a name, like this:
In this case, all files will be kept in the current directory.
Note: When choosing folder name, make sure there are no spaces or capital letters because of npm naming restrictions.
Once base application is created, if folder specified you just have to enter the folder. You can use this command to enter:
Then just start up the application with this command:
Features of React
1. JSX (JavaScript Syntax Extension):
- JSX combines HTML and JavaScript, allowing you to embed JavaScript objects within HTML elements.
- It enhances code readability and simplifies UI development.
Example:
const name = "GeekforGeeks";
const ele = <h1>Welcome to {name}</h1>;
2. Virtual DOM (Document Object Model):
- React uses a virtual DOM, which is an exact copy of the real DOM.
- When there are modifications in the web application, React updates the virtual DOM first and then computes the differences between the real DOM and the virtual DOM.
- This approach minimizes unnecessary re-rendering and improves performance.
3. One-way Data Binding:
- React follows one-way data binding, where data flows from parent components to child components.
- Child components cannot directly return data to their parent components, but they can communicate with parents to modify states based on provided inputs.
4. Performance:
- Separate components allow efficient rendering and faster execution.
5. Extension:
- React has a rich ecosystem and supports various extensions.
- Explore tools like Flux, Redux, and React Native for mobile app development and server-side rendering.
6. Conditional Statements in JSX:
- JSX allows writing conditional statements directly.
- Display data in the browser based on provided conditions.
Example:
const age = 12;
if (age >= 10) {
return <p>Greater than {age}</p>;
} else {
return <p>{age}</p>;
}
7. Components:
- React divides web pages into reusable and immutable components.
- Component-based development simplifies code organization and maintenance.
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. React is efficient, altering only what requires modification.
File Structure Breakdown
public/
:- This directory contains the
index.html
file and other static assets like images, fonts, or manifest files that need to be served as-is by the web server. index.html
: This is the main HTML file where your React application is initially rendered. It typically includes a<div>
or another HTML element where React will inject the application's UI.
- This directory contains the
src/
:This is where most of your application code resides, organized into several subdirectories:
assets/
:- Contains static assets such as images, fonts, SVG icons, or any other media files used in your application.
- Example:
assets/logo.png
,assets/background.jpg
.
components/
:- Contains reusable UI components that are used across different pages or sections of your application.
- Example:
Header.js
,Button.js
,Modal.js
. - These components are often designed to be modular and self-contained, promoting reusability and maintainability.
pages/
:- Each route or major section of your application has its own folder or file within this directory.
- Example:
Home.js
,About.js
,Contact.js
. - Pages typically represent different views or routes of your application and may use components from the
components/
directory.
services/
:- This directory contains services responsible for tasks like API integration, authentication, or other backend interactions.
- Example:
api.js
,authService.js
. - Services encapsulate logic related to data fetching, state management, or any other business logic that interacts with external systems.
styles/
:- Contains CSS files or preprocessor files (like Sass or Less) for styling your components.
- Example:
main.css
,variables.scss
. - Stylesheets define the visual appearance and layout of your application components.
utils/
:- Houses utility functions or helper modules used across your application.
- Example:
helpers.js
,constants.js
. - Utilities provide reusable functions or constants that assist in various tasks throughout your application.
App.js
:- This is the root component of your React application where routing and the main structure of your application are typically defined.
- It may include routes defined using React Router (
<BrowserRouter>
,<Switch>
,<Route>
), global layout components, or state management setup. - Example: Defining routes like
<Route path="/about" component={About} />
.
index.js
:- The entry point of your React application where the app is rendered into the DOM using
ReactDOM.render()
. - This file usually imports
App.js
and injects it into the HTML element specified inindex.html
. - Example:
ReactDOM.render(<App />, document.getElementById('root'));
.
node_modules/
: Contains all the npm packages required for your project.
Flow of the Project
Entry Point (
index.js
):- This file initializes your React application by rendering the
App
component into the DOM. - It typically imports
ReactDOM
fromreact-dom
and usesReactDOM.render()
to mount the root component (App
) onto the HTML page specified inpublic/index.html
.
- This file initializes your React application by rendering the
App.js
:- Acts as the main container for your application's structure and routing logic.
- Imports and uses components from
pages/
andcomponents/
directories to build different views and UI elements. - Sets up routing using React Router to navigate between different pages (
Route
,Switch
,BrowserRouter
).
Pages (
pages/
):- Each file (
Home.js
,About.js
, etc.) in this directory represents a specific view or route of your application. - These components use reusable UI components from
components/
and may fetch data from backend APIs via services fromservices/
.
- Each file (
Components (
components/
):- Reusable UI elements such as headers, footers, buttons, forms, etc., are stored here.
- These components are designed to be modular, making them easy to reuse across different pages or sections of your application.
Services (
services/
):- Contains modules responsible for API integration, authentication, state management, or any other backend-related tasks.
- These services are imported and used within components or pages to handle data fetching, state updates, or other asynchronous operations.
Styles and Assets:
- Styles (
styles/
): CSS or preprocessor files define the visual appearance and layout of your components. - Assets (
assets/
): Static resources such as images, fonts, or icons that are imported into components/pages as needed.
- Styles (
Key Differences:
Mutability:
sort
mutates the original array by rearranging its elements.map
,filter
, andreduce
do not mutate the original array; they return new arrays or values.- When we say that a method "mutates the original array," it means that the method directly modifies the array it is called upon, altering its contents or structure. This modification happens in-place, meaning the changes affect the original array itself, rather than creating a new array with the modified contents.
Return Value:
sort
returns a sorted version of the original array.map
,filter
, andreduce
return new arrays or values based on the transformations or conditions applied.
Usage:
sort
is primarily used for sorting elements based on custom criteria.map
,filter
, andreduce
are used for transforming, selecting, or aggregating data within arrays.
Functionality:
sort
requires a compare function to define the sorting order.map
andfilter
use a callback function to transform or filter elements based on conditions.reduce
applies a callback function to accumulate values into a single result.
These methods are fundamental for manipulating arrays in JavaScript, each serving distinct purposes depending on the desired operation.
1. Map
- What it does: It takes an array and applies a function to each element to create a new array where each element is transformed based on that function.
- Example: If you have an array of numbers
[1, 2, 3]
, and you usemap
with a function that doubles each number, you'll get[2, 4, 6]
.
Syntax:
let newArray = array.map(function(currentValue, index, array) {
// Return element for newArray
}, thisArg);
Example 1:
let arr = [45, 23, 21]
let a = arr.map(value, index, array)=> {
console.log(value, index, array);
return value + index ;
})
console.log(a);
Example 2:
let array=[11,22,33,44,55,66];
let arr2=array.map((value,index,array) =>
{
let product= value*index;
console.log(value,index,array,product);
return product;
);
console.log("original array=",array);
console.log("mapped array=",arr2);
Example 3(using object):
//for object using map()
let people =[{name:'pratiksha',age:20},
{name:'deep',age:15},
{name:'neel', age:16},
{name:'meet',age:14},
{name:'ved',age:10}];
let obj = people.map((value,index)=>
{
console.log(value,index,value.name);
return value;
});
// Doubling each number in the array
const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
return num * 2;
});
// doubled is [2, 4, 6]
console.log(doubled); // Output: [2, 4, 6]
Real Time Example :
Ans : Applying a Discount to a List of Product Prices
- Explanation of Syntax:
array
: The original array thatmap
was called upon (numbers
in this case).function(currentValue, index, array)
: A callback function thatmap
calls on each element ofarray
.currentValue
: The current element being processed in the array (num
in the example).index
(optional): The index of the current element being processed.array
(optional): The arraymap
was called upon (numbers
in this case).
thisArg
(optional): Optional. Value to use asthis
when executing the callback function.
2. Filter
- What it does: It takes an array and checks each element against a condition (specified by a function). It creates a new array containing only the elements that meet that condition.
- Example: If you have an array of numbers
[1, 2, 3, 4, 5]
, and you usefilter
with a function that checks for even numbers, you'll get[2, 4]
.
Syntax:
let newArray = array.filter(function(currentValue, index, array) {
// Return true if element passes the test
}, thisArg);
Example 1:
// Filtering even numbers from an array
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(function(num) {
return num % 2 === 0;
});
// evens is [2, 4]
console.log(evens); // Output: [2, 4]
Example 2 :
//object for filter()
let people =[{name:'Pratiksha',age:20},
{name:'Deep',age:15},
{name:'Neel', age:16},
{name:'Meet',age:14},
{name:'Ved',age:10}];
let obj = people.filter(function(age){
return age.age>15
});
console.log(obj);
Real time example :
Ans : Filtering Out Short Names
- Explanation of Syntax:
array
: The original array thatfilter
was called upon (numbers
in this case).function(currentValue, index, array)
: A callback function thatfilter
calls on each element ofarray
.currentValue
: The current element being processed in the array (num
in the example).index
(optional): The index of the current element being processed.array
(optional): The arrayfilter
was called upon (numbers
in this case).
thisArg
(optional): Optional. Value to use asthis
when executing the callback function.
3. Reduce
Example: If you have an array of numbers
[1, 2, 3, 4]
, and you use reduce
with a function that adds each number to an accumulator starting from 0, you'll get 10
(which is the sum of all numbers).- Syntax:
let result = array.reduce(function(accumulator, currentValue, index, array) {
// Return updated accumulator
}, initialValue);
Example:
// Summing all numbers in an array
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function(acc, current) {
return acc + current;
}, 0);
// sum is 10
console.log(sum); // Output: 10
Example 2 :
//reduce for array
let array = [2,5,8,1,2];let result = array.reduce((prev,current,index)=>{ // prev= current+ index; console.log("prev ", prev); console.log("current =", current); console.log("Iteration ",index) console.log("index =" ,index);
return prev + current;},10);
console.log(result);
Real Time Example :
Ans : Calculating the Product of a List
- Explanation of Syntax:
array
: The original array thatreduce
was called upon (numbers
in this case).function(accumulator, currentValue, index, array)
: A callback function thatreduce
calls on each element ofarray
, and uses to reduce the array to a single value.accumulator
: The accumulated result of previous iterations.currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arrayreduce
was called upon (numbers
in this case).
initialValue
: The initial value of the accumulator (0
in this example).
4. Sort
- What it does: It rearranges the elements of an array in a specific order (ascending or descending) based on a compare function you provide.
- Example: If you have an array of strings
['Banana', 'Orange', 'Apple']
, and you usesort
without any parameters, it will sort alphabetically, resulting in['Apple', 'Banana', 'Orange']
.
Syntax:
array.sort(function(firstElement, secondElement) {
// Return negative value if firstElement should come before secondElement
// Return positive value if firstElement should come after secondElement
// Return 0 if both elements are equal
});
Example 1:
let numbers = [4, 2, 5, 1, 3];
let newarray2 = numbers.sort((c,d) => c-d);let newarray3 = numbers.sort((c,d) => d-c);
console.log("og array=" ,numbers);console.log("asc",newarray2);console.log("desc",newarray3);
og array= [ 5, 4, 3, 2, 1 ]
asc [ 5, 4, 3, 2, 1 ]
desc [ 5, 4, 3, 2, 1 ]
Example 2:
// Sorting an array of strings alphabetically
const fruits = ['Banana', 'Orange', 'Apple'];
fruits.sort(); // ['Apple', 'Banana', 'Orange']
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']
Example 3 :
//sot() for object
let people =[{name:'Pratiksha',age:20},
{name:'Deep',age:15},
{name:'Neel', age:16},
{name:'Meet',age:14},
{name:'Ved',age:10}];
let newobj = people.sort((a,b) => a.name.localeCompare( b.name));
console.log(newobj);
Real time example :
Ans : Sorting Student Grades
- Explanation of Syntax:
array
: The array to be sorted (fruits
in this case).function(firstElement, secondElement)
: A compare function thatsort
uses to determine the order of elements.firstElement
,secondElement
: The two elements being compared.- The function should return:
- A negative value if
firstElement
should come beforesecondElement
. - A positive value if
firstElement
should come aftersecondElement
. 0
if both elements are considered equal in terms of sorting order.
- A negative value if
These examples cover basic usage and syntax for each array method (map
, filter
, reduce
, and sort
) in JavaScript, demonstrating how each method can be applied to arrays to achieve different transformations and operations.
map
when you need to transform elements in an array.filter
when you need to select elements based on a condition.reduce
when you need to aggregate data into a single value.sort
when you need to order elements based on certain criteria.JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript.
React JSX helps us to write HTML in JavaScript and forms the basis of React Development. Using JSX is not compulsory but it is highly recommended for programming in React as it makes the development process easier as the code becomes easy to write and read.
const element = <h1>This is sample JSX</h1>;
With the help of JSX, we have directly written the HTML syntax in JavaScript.
Why JSX ?
- It is faster than normal JavaScript.
- It makes it easier for us to create templates.
- Instead of separating the markup and logic in separate files, React uses components for this purpose. We will learn about components in detail in further articles.
- As JSX is an expression, we can use it inside of if statements and for loops, assign it to variables, accept it as arguments, or return it from functions.
1. Definition :
- Props are like arguments you pass to a function. They are read-only and passed from a parent component to a child component.
2. Purpose :
- Props are used to send data and functions to child components so that the parent can control how the child behaves.
State :
Key Concepts
- State Initialization: State is usually initialized in the constructor for class components or directly within the function for functional components using the
useState
hook. - State Updates: State updates are done using the
setState
method for class components or the setter function returned byuseState
in functional components. - State and Re-rendering: Changing the state triggers a re-render of the component, allowing the UI to update to reflect the new state.
1. Definition:
- State is an object that holds information that can change over time, controlled by the component itself.
2. Purpose:
- State is used to manage changing data inside a component and update the UI when the data changes.
setState
method in class components or the useState
hook in functional components.Add input and make a list usind map():
Comments
Post a Comment