React JS
Introducing React
JS
What is React JS?
React
JS, often simply referred to as React, is a JavaScript library for building
user interfaces, especially single-page applications where you need a fast,
interactive user experience. Developed by Facebook, it allows developers to
create reusable UI components and manage the state of these components
efficiently. React uses a virtual DOM to improve performance and facilitate a
smoother user experience.
What is a Scripting Language?
A
scripting language is a type of programming language designed for integrating
and communicating with other programming languages. They are usually used to
automate tasks that would otherwise be executed manually or to develop
applications that interact with other systems.
Advantages of Scripting Languages
- Ease
of Use:
Scripting languages often have simpler syntax compared to compiled
languages, making them easier to learn and use.
- Flexibility:
They allow quick changes and updates to scripts without needing a full
recompilation.
- Productivity:
They enable rapid development and testing of code, enhancing productivity.
- Integration:
They can easily interact with other software systems and languages.
Scripting Language Category
- Server-Side
Scripting Languages
- Examples:
PHP, Python, Ruby, Node.js
- Purpose:
Execute on the server to generate dynamic web content and handle
server-side logic.
- Client-Side
Scripting Languages
- Examples:
JavaScript, TypeScript
- Purpose:
Execute in the user's browser to create interactive web pages and manage
client-side operations.
Scripting vs Programming
- Scripting:
Typically used for automating tasks and often interpreted at runtime
(e.g., JavaScript, Python). They are usually embedded in other software or
used to control other applications.
- Programming:
Encompasses creating standalone applications with more complex structures
and functionalities (e.g., C++, Java). It involves both compiling and
interpreting code and usually includes building complex systems from
scratch.
What is JavaScript?
JavaScript
is a high-level, interpreted scripting language primarily used to create and
control dynamic content on websites. It allows developers to implement complex
features such as interactive forms, animations, and real-time updates.
What is JavaScript Used For?
- Client-Side
Web Development:
Enhancing user interactions and handling events within a web browser.
- Server-Side
Development:
Using environments like Node.js to build scalable network applications.
- Game
Development:
Creating interactive and engaging games.
- Mobile
Apps:
Using frameworks like React Native to build cross-platform mobile
applications.
What is a JavaScript Library?
A
JavaScript library is a collection of pre-written JavaScript code that
simplifies the development of common tasks. Libraries offer ready-to-use
functions and methods to make coding more efficient and modular. For example,
jQuery is a popular JavaScript library that simplifies DOM manipulation and
event handling.
What is the Difference Between a
JavaScript Library and a Framework?
- JavaScript
Library:
A library provides specific functions and methods that you can use to
accomplish particular tasks. You call the library's code when needed
(e.g., jQuery).
- Framework:
A framework provides a more comprehensive structure and set of conventions
for building applications. It often dictates the architecture and flow of
your application, and you work within its guidelines (e.g., Angular).
React JS vs Angular
- React
JS:
- Type:
Library focused on building UI components.
- Data
Binding:
One-way data binding.
- Learning
Curve:
Generally easier to learn due to its focus on view layer only.
- Flexibility:
Provides more flexibility, allowing developers to choose their tools and
libraries.
- Angular:
- Type:
Framework providing a complete solution for front-end development.
- Data
Binding:
Two-way data binding.
- Learning
Curve:
Steeper due to its comprehensive set of features and concepts.
- Opinionated:
More opinionated, providing a specific way to structure and build
applications.
Why React?
React
offers a component-based architecture that makes building complex UIs more
manageable. Its virtual DOM enhances performance by minimizing direct
manipulation of the real DOM, and its unidirectional data flow helps in
maintaining consistency.
Advantages of React JS | Features of
React
- Component-Based
Architecture:
Encourages reusable code and modular design.
- Virtual
DOM:
Improves performance by updating only parts of the DOM that have changed.
- One-Way
Data Binding:
Ensures that data flows in a single direction, making the code more
predictable.
- Rich
Ecosystem:
A robust ecosystem with tools like React Router and Redux for state
management.
Disadvantages of React JS | Limitations
of React
- Learning
Curve:
While the core library is straightforward, the ecosystem and additional
tools can be overwhelming.
- Boilerplate
Code:
Sometimes requires a significant amount of boilerplate code, especially
when integrating with other libraries.
- SEO
Challenges:
React’s client-side rendering can pose challenges for search engine
optimization, though this can be mitigated with server-side rendering
solutions.
Where to Use React JS
React
is ideal for building dynamic and interactive user interfaces, particularly for
single-page applications (SPAs) where efficient updates and a responsive user
experience are critical. It is also used for building mobile applications using
React Native.
What is a Single Page Application
(SPA)?
A
Single Page Application (SPA) is a type of web application that interacts with
the user by dynamically rewriting the current page rather than loading entire
new pages from the server. This approach provides a smoother, more responsive
user experience similar to a desktop application.
Summary
React
JS is a powerful JavaScript library for building dynamic user interfaces,
particularly suited for single-page applications. Unlike full frameworks like
Angular, React focuses on the view layer and provides a component-based
architecture that enhances performance and code maintainability. JavaScript,
the core language React is built on, is widely used for both client-side and
server-side development. Understanding the distinction between libraries and
frameworks, as well as the specific advantages and limitations of React, helps
developers make informed decisions about when and how to use this tool
effectively.
Setup Environment for React JS
Setting
up a React JS development environment involves configuring various tools and
utilities to create and manage React applications efficiently. Below is a
step-by-step guide on setting up a React JS project, including using CDN links
and setting up a local development environment.
1. How to Setup React JS Project Using
CDN Links
Using
CDN Links
is a quick way to start experimenting with React without installing any
additional tools. This method is suitable for learning and small projects but
is less practical for larger, production-ready applications.
Steps:
- Create
an HTML File:
Create a new HTML file (e.g., index.html)
and add the following code:
Html
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>React with CDN</title>
<script
src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script
src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script
src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const App = () => {
return <h1>Hello, React with
CDN!</h1>;
};
ReactDOM.render(<App />,
document.getElementById('root'));
</script>
</body>
</html>
- Open
in Browser:
Open the HTML file in a web browser, and you should see "Hello, React
with CDN!" rendered on the page.
2. Basic Requirements to Set Up
Development Environment
To
create and manage React applications efficiently in a professional development
environment, you will need several tools.
Text Editor/Source Code Editor
- Visual
Studio Code (VS Code): A popular and versatile text
editor with features like syntax highlighting, IntelliSense, and
integrated terminal.
- Download
& Install:
Visual Studio
Code
Web Browser
- Recommended
Browsers:
Chrome, Firefox, Edge, or any modern browser.
- Recommended
Extension:
React Developer Tools for inspecting React components.
React Developer Tool
- Purpose:
Helps in debugging React applications by providing an interface to inspect
React component hierarchy and state.
- Installation:
- Chrome:
Install the React Developer Tools extension from the Chrome Web Store.
- Firefox:
Install the React
Developer Tools extension from Firefox Add-ons.
NPM (Node Package Manager)
- Purpose:
Manages JavaScript packages and dependencies for React and other
libraries.
- Installation:
Comes with Node.js.
Download and install Node.js, which includes npm.
Webpack
- Purpose:
A module bundler that helps in bundling JavaScript files and other assets
(like CSS and images) for deployment.
- Installation:
Install Webpack locally in your project using npm.
Bash
npm
install --save-dev webpack webpack-cli
Babel
- Purpose:
Transpiles modern JavaScript (including JSX used in React) into a version
compatible with older browsers.
- Installation:
Install Babel along with its presets and plugins.
Bash
npm
install --save-dev @babel/core @babel/cli @babel/preset-env @babel/preset-react
3. Complete Visual Studio Code Setup
1.
Install VS Code Extensions:
- ESLint:
Linting tool for maintaining code quality.
- Prettier:
Code formatter to ensure consistent code style.
- Reactjs
code snippets:
Provides useful code snippets for React development.
- Bracket
Pair Colorizer:
Helps in visualizing matching brackets.
2.
Configure VS Code:
- Settings:
Configure settings like formatting on save, linting rules, and snippet
preferences in your workspace settings or user settings.
Example
Configuration (settings.json):
Json
{
"editor.formatOnSave": true,
"eslint.validate":
["javascript", "javascriptreact"],
"prettier.singleQuote": true,
"javascript.format.enable": false
}
4. Complete NPM Setup
1.
Initialize a New React Project: Use Create React App (CRA) to set up a
new React project with a single command.
Bash
npx
create-react-app my-app
cd
my-app
npm
start
2.
Project Structure:
- public/:
Contains static files like index.html.
- src/:
Contains React components, styles, and other JavaScript files.
- package.json:
Manages project dependencies and scripts.
5. How to Install React Developer Tool
1.
Chrome:
- Open
Chrome and navigate to the React Developer Tools extension page.
- Click
"Add to Chrome" and follow the prompts.
2.
Firefox:
- Open
Firefox and go to the React Developer
Tools
add-ons page.
- Click
"Add to Firefox" and follow the prompts.
Using
the Tool:
- After
installation, you can access the React DevTools in the browser’s developer
tools panel. This provides a new "Components" and
"Profiler" tab for inspecting and profiling React components.
Summary
Setting
up a React development environment involves choosing the right tools and
configuring them appropriately. For a quick start, you can use CDN links to
include React in your HTML files. For a more robust setup, you’ll need a text
editor like Visual Studio Code, a web browser with React Developer Tools, npm
for managing dependencies, and tools like Webpack and Babel for bundling and
transpiling code. Using Create React App simplifies the initial setup, and installing
necessary VS Code extensions and configuring npm enhances the development
experience.
Setup/Create React
JS Project
Creating
a React JS project involves setting up the environment and understanding how
React manages its components and state. Below is a comprehensive guide to
setting up and understanding React projects.
1. How to Setup/Create React JS Project
Using NPM
Using the create-react-app
Command
create-react-app
is a command-line tool that sets up a new React project with a preconfigured
build setup. It simplifies the initial setup by handling the configuration of
Webpack, Babel, and other development tools.
Steps:
- Install
Node.js and npm:
Ensure you have Node.js and npm installed. You can download and install
them from nodejs.org.
- Create
a New React Project: Open your terminal or command
prompt and run:
Bash
npx
create-react-app my-app
Replace my-app
with your desired project name.
- Navigate
to Project Directory:
Bash
cd
my-app
- Start
the Development Server:
Bash
npm
start
This will start the development server
and open your new React app in the default web browser.
Using the NPM Command (Using Webpack
and Babel)
If
you want to set up React manually using Webpack and Babel, you need to
configure these tools yourself. This method offers more control over the setup
but requires more configuration.
Steps:
- Create
a New Directory:
Bash
mkdir
my-app
cd
my-app
- Initialize
npm:
Bash
npm
init -y
- Install
React and ReactDOM:
Bash
npm
install react react-dom
- Install
Webpack and Babel:
Bash
npm
install --save-dev webpack webpack-cli webpack-dev-server babel-loader
@babel/core @babel/preset-env @babel/preset-react html-webpack-plugin
- Create
Configuration Files:
- webpack.config.js:
js
const
path = require('path');
const
HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports
= {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env',
'@babel/preset-react'],
},
},
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
}),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
},
};
- .babelrc:
Json
{
"presets":
["@babel/preset-env", "@babel/preset-react"]
}
- Create
Project Structure:
- /src/index.js:
Js
import
React from 'react';
import
ReactDOM from 'react-dom';
import
App from './App';
ReactDOM.render(<App
/>, document.getElementById('root'));
- /src/App.js:
Js
import
React from 'react';
const
App = () => {
return <h1>Hello, React with Webpack
and Babel!</h1>;
};
export
default App;
- /public/index.html:
Html
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
- Start
the Development Server:
Bash
npx
webpack serve
2. React JS Folder Structure
Typical
folder structure:
- public/:
Contains static files like index.html.
- src/:
Contains all source code files.
- index.js:
Entry point for the React application.
- App.js:
Main component for the application.
- components/:
Folder for React components.
- styles/:
Folder for CSS or style files.
3. DOM vs Virtual DOM
- DOM
(Document Object Model): Represents the
structure of the HTML document as a tree of objects. Every change in the
UI directly manipulates the DOM, which can be slow if the changes are
frequent or complex.
- Virtual
DOM:
A lightweight in-memory representation of the actual DOM. React maintains
a virtual DOM to optimize performance by minimizing direct interactions
with the actual DOM.
4. How is Virtual DOM Faster?
The
Virtual DOM improves performance by:
- Batching
Updates:
React batches multiple updates to the virtual DOM and applies them in a
single operation.
- Efficient
Diffing Algorithm: React compares the current
virtual DOM with the previous one using a diffing algorithm to determine
the minimal set of changes required.
- Selective
Updates:
Only updates the parts of the real DOM that have changed, rather than
re-rendering the entire DOM.
5. How Does React Use Virtual DOM?
React
uses the Virtual DOM as follows:
- Render
Method:
When a component’s state or props change, React creates a new Virtual DOM
tree.
- Diffing:
React compares the new Virtual DOM tree with the previous one to determine
changes.
- Reconciliation:
React applies the necessary changes to the actual DOM based on the diffing
results, ensuring efficient updates.
6. Strict Mode in React JS
Purpose:
React’s StrictMode is a development tool that helps identify potential problems
in an application. It activates additional checks and warnings for its
descendants.
Usage:
Js
import
React from 'react';
import
ReactDOM from 'react-dom';
import
App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Benefits:
- Identifies
components with unsafe lifecycle methods.
- Warns
about deprecated APIs.
- Helps
detect unexpected side effects.
7. Extends and Implements in React JS
- Extends:
In React, components typically extend React.Component
to create class components. This allows the component to inherit methods
and properties from React.Component.
Js
class
MyComponent extends React.Component {
render() {
return <div>Hello,
World!</div>;
}
}
- Implements:
React components don’t use interfaces in the same way as other languages
like TypeScript or Java. Instead, React components are either class-based
or functional.
8. render()
Methods
- Class
Components:
The render()
method is required in class components and returns the JSX to be
displayed.
Js
class
MyComponent extends React.Component {
render() {
return <div>Hello,
World!</div>;
}
}
- Functional
Components:
Don’t require a render()
method. The function itself returns the JSX.
js
Copy
code
const
MyComponent = () => <div>Hello, World!</div>;
9. React Elements
Definition:
React elements are the smallest building blocks of React apps. They describe what
should appear on the screen. Elements are immutable and can be created using React.createElement()
or JSX.
- createElement()
Method:
js
const
element = React.createElement('h1', null, 'Hello, World!');
10. ReactDOM.render()
Method
Purpose:
The ReactDOM.render()
method is used to render a React element or component into a specified DOM
container.
Example:
Js
import
React from 'react';
import
ReactDOM from 'react-dom';
import
App from './App';
ReactDOM.render(<App
/>, document.getElementById('root'));
This
code mounts the App
component into the DOM element with the ID root.
11. JSX (JavaScript XML)
Definition:
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows
developers to write HTML elements and components in a JavaScript file.
Example:
Js
const
element = <h1>Hello, World!</h1>;
How
it Works:
- JSX
gets transpiled into JavaScript code using Babel.
- Transpiled
code uses React.createElement()
to create React elements.
Transpiled
Example:
Js
const
element = React.createElement('h1', null, 'Hello, World!');
Summary
Creating
a React JS project involves several steps depending on the setup method. Using create-react-app
simplifies the process by providing a pre-configured environment.
Alternatively, setting up with Webpack and Babel offers more control but
requires additional configuration. Understanding the folder structure, DOM vs.
Virtual DOM, and React’s rendering process is crucial for effective
development. The Virtual DOM improves performance by minimizing direct DOM
manipulation, and React’s tools like StrictMode help in identifying potential
issues. JSX makes writing
Module Import -
Export
Understanding
module import and export is crucial for structuring and organizing code in
modern JavaScript applications. This guide explains modules, export and import
mechanisms, and their various types.
What is a Module?
A
module is a self-contained piece of code that can be reused across different
parts of an application. It encapsulates functionality by exporting data,
functions, or classes and importing them into other files. Modules help in
organizing code into manageable sections and promote code reuse.
What is Export?
The
export
keyword is used to expose variables, functions, or classes from a module so
they can be imported and used in other modules. There are two main types of
exports in JavaScript: default exports and named exports.
Module - Export
Types of Export
- Default
Export
- A
module can have one default export. Default exports are useful when you
want to export a single entity from a module.
- Syntax:
Js
//
file: module.js
const
greeting = 'Hello, World!';
export
default greeting;
- Named
Export
- A
module can have multiple named exports. Named exports are used to export
multiple entities from a module, each with its own name.
- Syntax:
Js
//
file: module.js
export
const greeting = 'Hello, World!';
export
const farewell = 'Goodbye, World!';
Module - Default Export
Example:
Js
//
file: math.js
const
add = (a, b) => a + b;
export
default add;
Usage:
Js
//
file: app.js
import
add from './math';
console.log(add(2,
3)); // Output: 5
Module - Named Export
Example:
Js
//
file: math.js
export
const add = (a, b) => a + b;
export
const subtract = (a, b) => a - b;
Usage:
Js
//
file: app.js
import
{ add, subtract } from './math';
console.log(add(2,
3)); // Output: 5
console.log(subtract(5,
3)); // Output: 2
Module - Import
Types of Import
- Default
Import
- Used
to import the default export from a module.
- Syntax:
Js
import
someVariable from './module';
- Named
Import
- Used
to import specific named exports from a module.
- Syntax:
Js
import
{ someVariable } from './module';
Module - Importing Default
Example:
Js
//
file: math.js
const
multiply = (a, b) => a * b;
export
default multiply;
Usage:
Js
//
file: app.js
import
multiply from './math';
console.log(multiply(2,
3)); // Output: 6
Module - Importing Named
Example:
Js
//
file: math.js
export
const divide = (a, b) => a / b;
Usage:
Js
//
file: app.js
import
{ divide } from './math';
console.log(divide(6,
3)); // Output: 2
Module - Importing All
- Purpose:
Allows importing all named exports from a module as a single object.
- Syntax:
Js
import
* as math from './math';
Example:
Js
//
file: math.js
export
const add = (a, b) => a + b;
export
const subtract = (a, b) => a - b;
Usage:
Js
//
file: app.js
import
* as math from './math';
console.log(math.add(2,
3)); // Output: 5
console.log(math.subtract(5,
3)); // Output: 2
Module - Importing Default & Named
Example:
Js
//
file: math.js
const
multiply = (a, b) => a * b;
const
divide = (a, b) => a / b;
export
default multiply;
export
{ divide };
Usage:
Js
//
file: app.js
import
multiply, { divide } from './math';
console.log(multiply(2,
3)); // Output: 6
console.log(divide(6,
3)); // Output: 2
Summary
Modules
in JavaScript help organize code by encapsulating functionality and allowing it
to be shared across different parts of an application. Using the export
keyword, you can expose variables, functions, or classes from a module, and
with the import
keyword, you can bring these entities into other modules. There are two primary
types of exports: default and named, and corresponding import types: default
import, named import, and importing all named exports. Understanding these
concepts allows for better modularization, code reuse, and maintainability in JavaScript
applications.
ES6/ES7/ES8: Key
Features and Concepts
ECMAScript
(often abbreviated as ES) is the standard specification that JavaScript
follows. New versions of ECMAScript introduce various features and improvements
to the language. Let's delve into some of the key features introduced in ES6
(ECMAScript 2015), ES7 (ECMAScript 2016), and ES8 (ECMAScript 2017).
1. What is ECMAScript?
ECMAScript
is a scripting language specification that JavaScript adheres to. It
standardizes the core features of JavaScript and is maintained by ECMA
International. Each edition of ECMAScript introduces new features and
improvements.
2. ECMAScript Editions
- ES5
(ECMAScript 5):
Published in 2009, it introduced features like strict
mode,
JSON support, and more array methods.
- ES6
(ECMAScript 2015): Introduced major features such as
let,
const,
arrow functions, and classes.
- ES7
(ECMAScript 2016): Added features like the
exponentiation operator and Array.prototype.includes.
- ES8
(ECMAScript 2017): Introduced async functions, Object.entries(),
Object.values(),
and more.
3. var,
let,
& const
- var:
Function-scoped variable declaration. Variables declared with var
can be re-declared and updated within their scope.
Js
var
x = 10;
if
(true) {
var x = 20; // same variable
}
console.log(x);
// Output: 20
- let:
Block-scoped variable declaration. Variables declared with let
cannot be re-declared within the same scope.
Js
let
y = 10;
if
(true) {
let y = 20; // different variable
}
console.log(y);
// Output: 10
- const:
Block-scoped constant declaration. Variables declared with const
must be initialized and cannot be reassigned.
Js
const
z = 10;
//
z = 20; // Error: Assignment to constant variable.
4. Template Literals in JavaScript
Template
literals provide a way to embed expressions into strings and create multi-line
strings. They use backticks (`) instead of quotes.
Example:
Js
const
name = 'Alice';
const
greeting = `Hello, ${name}!`;
console.log(greeting);
// Output: Hello, Alice!
Methods:
- Tagged
Templates:
Allows customization of template literals.
Js
function
tag(strings, ...values) {
console.log(strings, values);
}
tag`Hello
${name}`; // Outputs: ["Hello ", ""], ["Alice"]
5. Array Destructuring
Array
destructuring allows unpacking values from arrays into distinct variables.
Example:
Js
const
[a, b] = [1, 2];
console.log(a,
b); // Output: 1 2
With
Default Values:
Js
const
[x = 10, y = 20] = [1];
console.log(x,
y); // Output: 1 20
6. Object Destructuring
Object
destructuring allows unpacking properties from objects into distinct variables.
Example:
Js
const
person = { name: 'John', age: 30 };
const
{ name, age } = person;
console.log(name,
age); // Output: John 30
With
Default Values:
Js
const
{ name = 'Unknown', age = 0 } = {};
console.log(name,
age); // Output: Unknown 0
7. Default Parameters
Default
parameters allow functions to have default values if no arguments are provided.
Example:
Js
function
greet(name = 'Guest') {
return `Hello, ${name}`;
}
console.log(greet());
// Output: Hello, Guest
8. Rest Parameters
Rest
parameters allow functions to accept an indefinite number of arguments as an
array.
Example:
Js
function
sum(...numbers) {
return numbers.reduce((acc, curr) => acc +
curr, 0);
}
console.log(sum(1,
2, 3, 4)); // Output: 10
9. Fat Arrow Function
Arrow
functions provide a shorter syntax for writing functions and inherit the this
value from their enclosing context.
Example:
Js
const
add = (a, b) => a + b;
console.log(add(2,
3)); // Output: 5
Without
Parameters:
Js
const
greet = () => 'Hello';
console.log(greet());
// Output: Hello
10. Spread Operator
The
spread operator (...)
allows expanding elements of an array or object into individual elements.
Example
with Arrays:
Js
const
nums = [1, 2, 3];
const
moreNums = [0, ...nums, 4];
console.log(moreNums);
// Output: [0, 1, 2, 3, 4]
Example
with Objects:
Js
const
obj1 = { a: 1, b: 2 };
const
obj2 = { ...obj1, c: 3 };
console.log(obj2);
// Output: { a: 1, b: 2, c: 3 }
11. Math.sign()
Returns
the sign of a number, indicating whether it is positive, negative, or zero.
Example:
Js
console.log(Math.sign(-10));
// Output: -1
console.log(Math.sign(0)); // Output: 0
console.log(Math.sign(10)); // Output: 1
12. Math.trunc()
Returns
the integer part of a number by removing any fractional digits.
Example:
Js
console.log(Math.trunc(4.9));
// Output: 4
console.log(Math.trunc(-4.9));
// Output: -4
13. Exponentiation Operator
The
exponentiation operator (**)
raises the base to the exponent power.
Example:
Js
console.log(2
** 3); // Output: 8
14. Numbers & Global Methods
- isFinite()
Method:
Checks if a value is a finite number.
Example:
Js
console.log(isFinite(2
/ 0)); // Output: false
console.log(isFinite(2
/ 1)); // Output: true
- isNaN()
Method:
Checks if a value is NaN (Not-a-Number).
Example:
Js
console.log(isNaN('hello'));
// Output: true
console.log(isNaN(123)); // Output: false
- Number.isInteger()
Method:
Checks if a value is an integer.
Example:
Js
console.log(Number.isInteger(4));
// Output: true
console.log(Number.isInteger(4.5));
// Output: false
15. Class
Classes
provide a blueprint for creating objects with shared properties and methods.
They simplify the creation of objects and inheritance.
Example:
Js
class
Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
const
person = new Person('Alice', 30);
console.log(person.greet());
// Output: Hello, my name is Alice
16. Callback Hell in JavaScript
Callback
hell refers to the situation where multiple nested callbacks make code
difficult to read and maintain.
Example:
Js
doSomething(function(err,
result) {
if (err) {
// handle error
} else {
doSomethingElse(result, function(err,
result) {
if (err) {
// handle error
}
else {
// more nested callbacks
}
});
}
});
17. Promises in JavaScript
Promises
represent the eventual completion (or failure) of an asynchronous operation and
its resulting value.
Example:
Js
const
promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Done!'), 1000);
});
promise.then(result
=> console.log(result)); // Output: Done!
18. Async Await in JavaScript
Async/await
syntax simplifies working with promises by making asynchronous code look
synchronous.
Example:
Js
async
function fetchData() {
const response = await
fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
fetchData().then(data
=> console.log(data));
19. Generators in ES6 JavaScript
- Normal
Functions:
Execute from start to finish and return a result.
- Generators:
Special type of function that can be paused and resumed. They use the function*
syntax and yield
keyword.
Example:
Js
function*
generator() {
yield 1;
yield 2;
yield 3;
}
const
gen = generator();
console.log(gen.next().value);
// Output: 1
console.log(gen.next().value);
// Output: 2
console.log(gen.next().value);
// Output: 3
Summary
ECMAScript
introduces enhancements to JavaScript, with ES6, ES7, and ES8 bringing
significant improvements. Key features include:
- Variables:
let
and const
for block-scoped variables, var
for function-scoped.
- Template
Literals:
For easier string interpolation and multi-line strings.
- Destructuring:
For easier extraction of values from arrays and objects.
- Default
and Rest Parameters: For handling function arguments.
- Arrow
Functions and Spread Operator: For concise
syntax and expanded functionality.
- Math
Methods and Class Syntax: For better
mathematical operations and object-oriented programming.
- Async/Await
and Promises:
For handling asynchronous operations more effectively.
JSX in Depth
JSX
(JavaScript XML) is a syntax extension for JavaScript commonly used with React.
It allows you to write HTML-like code within JavaScript, making it easier to create
React elements and components. Let’s explore JSX in depth, including its
syntax, features, and common practices.
1. JSX: Single Element
JSX
allows you to create React elements using an HTML-like syntax. Each JSX
expression must have a single root element.
Example:
Jsx
const
element = <h1>Hello, world!</h1>;
This
JSX code represents a React element that renders an <h1>
HTML element with the text "Hello, world!".
2. JSX: Nested Elements
You
can nest JSX elements within each other to build more complex UIs. Just like
HTML, JSX supports nested tags.
Example:
Jsx
const
element = (
<div>
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
</div>
);
Here,
the <div>
element contains an <h1>
and a <p>
element.
3. Expressions in JSX
JSX
allows you to embed JavaScript expressions inside curly braces {}.
This is useful for dynamically inserting values.
Example:
Jsx
const
name = 'Alice';
const
element = <h1>Hello, {name}!</h1>;
The
{name}
expression evaluates to "Alice", so the rendered output is <h1>Hello,
Alice!</h1>.
4. Elements Must Be Closed
In
JSX, every tag must be properly closed. This includes self-closing tags like <img>
or <input>.
Example:
Jsx
const
element = (
<div>
<img src="logo.png"
alt="Logo" />
<input type="text" />
</div>
);
In
this example, both <img>
and <input>
are self-closing and must end with a slash (/).
5. Attributes
Attributes
in JSX are similar to HTML attributes but with some differences.
As String Literals
Attributes
can be set as string literals, just like in HTML.
Example:
Jsx
const
element = <a href="https://www.example.com">Example</a>;
As Expressions
You
can use curly braces {}
to embed JavaScript expressions in attributes.
Example:
Jsx
const
link = 'https://www.example.com';
const
element = <a href={link}>Example</a>;
Here,
the href
attribute is set using a JavaScript variable.
6. The style
Attribute Changes Its Semantics
In
JSX, inline styles are specified as an object rather than a string.
Example:
Jsx
const
style = { color: 'blue', backgroundColor: 'lightgray' };
const
element = <div style={style}>Styled Text</div>;
Here,
the style
attribute is an object with camelCase properties.
7. Comments
You
can add comments in JSX using curly braces {}.
Example:
Jsx
const
element = (
<div>
{/* This is a comment */}
<h1>Hello, world!</h1>
</div>
);
Comments
inside JSX are wrapped in curly braces and are useful for adding notes or
explanations.
8. JSX Does Not Allow if-else
Statements
JSX
does not support if-else
statements directly. Instead, you can use conditional expressions like the
ternary operator or logical operators.
Example
with Ternary Operator:
Jsx
const
isLoggedIn = true;
const
element = (
<div>
{isLoggedIn ? <p>Welcome
back!</p> : <p>Please log in.</p>}
</div>
);
Example
with Logical &&
Operator:
Jsx
const
showMessage = true;
const
element = (
<div>
{showMessage && <p>This will
be shown if true.</p>}
</div>
);
9. camelCase is the New Standard
JSX
attributes use camelCase rather than the lowercase style used in HTML. For
example, class
in HTML becomes className
in JSX.
Example:
Jsx
const
element = <div className="my-class">Hello</div>;
10. Naming Convention
When
using JSX, adhere to naming conventions:
- Use
camelCase for attribute names.
- Use
PascalCase for component names.
Example:
Jsx
function
MyComponent() {
return <div
className="my-component">Content</div>;
}
11. How to Loop in JSX
To
loop through data in JSX, you typically use JavaScript’s array methods like map().
This allows you to dynamically generate elements based on data.
Example:
Jsx
const
items = ['Apple', 'Banana', 'Cherry'];
const
listItems = items.map((item, index) => <li
key={index}>{item}</li>);
const
element = (
<ul>
{listItems}
</ul>
);
In
this example, items.map()
creates a list of <li>
elements, each representing an item from the items
array.
Summary
JSX
extends JavaScript by allowing you to write HTML-like syntax within JavaScript.
It simplifies the process of creating and managing React elements and
components. Key points include:
- Single
and Nested Elements: JSX can represent a single root
element or nested elements.
- Expressions:
JavaScript expressions can be embedded within JSX.
- Element
Closure:
All JSX tags must be properly closed.
- Attributes:
Attributes in JSX can be string literals or expressions.
- Inline
Styles:
The style
attribute uses JavaScript objects.
- Comments:
Comments are added using curly braces.
- Conditional
Rendering:
Use ternary operators or logical operators for conditional rendering.
- camelCase:
JSX attributes use camelCase naming conventions.
- Looping:
Use JavaScript array methods like map()
to dynamically generate elements.
Babel in React JS
What is Babel?
Babel
is a JavaScript compiler that is widely used in modern web development to
convert code written in ECMAScript 6 (or higher) and JSX (a syntax extension
used in React) into JavaScript that is compatible with older browsers or
environments.
Key Functions of Babel:
- Transform
Syntax:
Babel can convert newer JavaScript syntax into older syntax that is more
broadly supported by different browsers. For example, it can convert arrow
functions and classes into ES5 syntax.
- Polyfill
Features:
Babel can include polyfills for newer JavaScript features that aren't
natively supported in the target environment. This ensures that the code
can use features like Array.prototype.includes
or Promise
without breaking in older environments.
- Convert
JSX Syntax:
JSX is a syntax extension for JavaScript that looks similar to HTML and is
used in React to describe what the UI should look like. Babel transforms
JSX into regular JavaScript function calls (e.g., React.createElement),
making it possible for browsers to understand and render React components.
Webpack in React JS
What is Webpack?
Webpack
is a module bundler for JavaScript applications. It takes modules with
dependencies and generates static assets representing those modules. In the
context of React, Webpack bundles JavaScript files, CSS, and other assets,
making it possible to load them efficiently.
Key Functions of Webpack:
- Bundling:
Webpack combines all the JavaScript modules, styles, and assets into a
single or a few bundled files. This helps in reducing the number of HTTP
requests and improving load times.
- Loaders:
Loaders in Webpack allow you to preprocess files before they are added to
the bundle. For example, you can use Babel with a Webpack loader to transpile
JSX and ES6 code into ES5.
- Plugins:
Webpack plugins can be used to optimize the build process, such as
minifying the code, generating source maps, or defining environment
variables.
Real-Time Example
Imagine
you have a React application with some JSX and ES6 features:
- Code
Example:
Jsx
//
src/App.js
import
React from 'react';
const
App = () => (
<div>
<h1>Hello, World!</h1>
<p>Welcome to React with Webpack and
Babel!</p>
</div>
);
export
default App;
- Webpack
Configuration:
Your Webpack configuration might look like this:
Javascript
//
webpack.config.js
const
path = require('path');
module.exports
= {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react',
'@babel/preset-env']
}
}
}
]
}
};
- Babel
Configuration:
Your Babel configuration might be in a .babelrc
file:
Json
{
"presets":
["@babel/preset-react", "@babel/preset-env"]
}
In
this setup:
- Webpack
bundles all your JavaScript files, including React components.
- Babel
transpiles JSX and ES6 syntax to ensure compatibility with older browsers.
Summary
- Babel
is a JavaScript compiler used to convert modern JavaScript and JSX into
compatible code for older environments. It transforms syntax, polyfills
features, and converts JSX to JavaScript.
- Webpack
is a module bundler that combines various assets, such as JavaScript files
and stylesheets, into a single or few bundles. It uses loaders to
preprocess files (like using Babel to transpile code) and plugins to
optimize the build.
React JS Overview
React
is a popular JavaScript library for building user interfaces, primarily for
single-page applications where you need a fast, interactive user experience.
Components in React JS
Types of Components
- Functional
Components:
- Defined
as JavaScript functions that return JSX.
- Example:
Jsx
function
Greeting(props) {
return <h1>Hello,
{props.name}!</h1>;
}
- Class
Components:
- ES6
classes that extend React.Component.
- Example:
Jsx
class
Greeting extends React.Component {
render() {
return <h1>Hello,
{this.props.name}!</h1>;
}
}
Component Constructor
- Purpose:
Initializes state and binds methods in class components.
- Example:
Jsx
class
MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}
Components in Components
- Components
can be nested inside other components to build a tree of components.
Props in React JS
Props Data Types
- String,
Integer, Boolean, Array, Object, Function
Props in Function-Based Component
- Accessed
via function parameters.
Jsx
function
Greeting(props) {
return <h1>Hello,
{props.name}!</h1>;
}
Props in Class-Based Component
- Accessed
via this.props.
Jsx
class
Greeting extends React.Component {
render() {
return <h1>Hello,
{this.props.name}!</h1>;
}
}
Props are Read-Only
- Props
cannot be modified by the component receiving them.
Default Props
- Provide
default values for props.
Jsx
Greeting.defaultProps
= {
name: 'Stranger'
};
Children Props (props.children)
- Allows
passing child elements to a component.
Jsx
function
Container(props) {
return
<div>{props.children}</div>;
}
PropTypes in React JS
- PropTypes
help validate props passed to a component.
Jsx
import
PropTypes from 'prop-types';
MyComponent.propTypes
= {
name: PropTypes.string,
age: PropTypes.number.isRequired
};
State in React JS
Creating and Initializing State
- Directly
in Class Component:
Jsx
class
MyComponent extends React.Component {
state = { count: 0 };
}
- Inside
Constructor:
jsx
Copy
code
class
MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
}
Changing State
- Using
setState():
jsx
Copy
code
this.setState({
count: this.state.count + 1 });
State vs. Props
- Props:
Passed from parent to child components, read-only.
- State:
Managed within a component, mutable.
React Events
Adding Events
- React
Event Declaration:
Jsx
<button
onClick={this.handleClick}>Click Me</button>
Bind this
- Binding
in Constructor:
Jsx
constructor(props)
{
super(props);
this.handleClick =
this.handleClick.bind(this);
}
- Arrow
Functions:
Jsx
<button
onClick={() => this.handleClick()}>Click Me</button>
Supported Events
- React
supports most HTML events like onClick,
onChange,
etc.
React Conditional Rendering
- If:
Jsx
if
(this.state.isLoggedIn) {
return <Welcome />;
}
else {
return <Login />;
}
- Element
Variables:
Jsx
const
element = this.state.isLoggedIn ? <Welcome /> : <Login />;
- Logical
&&
Operator:
Jsx
{this.state.isLoggedIn
&& <Welcome />}
- Ternary
Operator:
Jsx
{this.state.isLoggedIn
? <Welcome /> : <Login />}
- Switch
Case:
Jsx
switch
(this.state.page) {
case 'home':
return <Home />;
case 'about':
return <About />;
default:
return <NotFound />;
}
React Lists and Keys
Using map()
in JSX
- Example:
Jsx
const
numbers = [1, 2, 3, 4];
const
listItems = numbers.map((number) =>
<li
key={number.toString()}>{number}</li>
);
Keys
- Using
Index
(not recommended for dynamic lists):
Jsx
<li
key={index}>{item}</li>
- Using
ID
(preferred):
Jsx
<li
key={item.id}>{item.name}</li>
React Styling
Inline CSS
- Example:
Jsx
<div
style={{ color: 'red' }}>Hello World</div>
Normal CSS (External Stylesheet)
- Importing
CSS:
Jsx
import
'./App.css';
CSS Modules
- Usage:
Jsx
import
styles from './App.module.css';
<div
className={styles.container}>Hello World</div>
CSS-in-JS
- Using
Libraries:
Styled-components, Emotion
React Router
Installation
- Command:
Bash
npm
install react-router-dom
Routes
- Defining
Routes:
Jsx
<Route
path="/about" component={About} />
Navigation
- Using
Link
Component:
Jsx
<Link
to="/about">About</Link>
404 Page
- Adding
a 404 Page:
Jsx
<Route
path="*" component={NotFound} />
Hooks in React JS
Use Cases
- For
managing state and side effects in functional components.
Built-in Hooks
- useState:
jsx
const
[count, setCount] = useState(0);
- useEffect:
jsx
useEffect(()
=> {
document.title = `You clicked ${count}
times`;
},
[count]);
- useContext:
jsx
const
context = useContext(MyContext);
Custom Hook
- Example:
Jsx
function
useWindowWidth() {
const [width, setWidth] =
useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize',
handleResize);
return () =>
window.removeEventListener('resize', handleResize);
}, []);
return width;
}
Context API
Using useContext
- Example:
Jsx
const
MyContext = React.createContext();
const
value = useContext(MyContext);
Multiple Contexts
- Combining
Contexts:
Jsx
const
combinedContext = useContext(ContextA) || useContext(ContextB);
useReducer
Hook
- Example:
Jsx
const
[state, dispatch] = useReducer(reducer, initialState);
Forms in React JS
Controlled Components
- Example:
Jsx
function
MyForm() {
const [value, setValue] = useState('');
return (
<input type="text"
value={value} onChange={(e) => setValue(e.target.value)} />
);
}
Uncontrolled Components
- Example:
Jsx
function
MyForm() {
const inputRef = useRef();
const handleSubmit = () => {
alert(inputRef.current.value);
};
return (
<div>
<input type="text"
ref={inputRef} />
<button
onClick={handleSubmit}>Submit</button>
</div>
);
}
React Component Lifecycle
Mounting
- Methods:
constructor(),
render(),
componentDidMount()
Updating
- Methods:
shouldComponentUpdate(),
componentDidUpdate()
Unmounting
- Method:
componentWillUnmount()
React Component API
setState()
- Usage:
Jsx
this.setState({
key: value });
forceUpdate()
- Usage:
Jsx
this.forceUpdate();
Consuming APIs
Fetch API
- Example:
Jsx
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
Introduction to
Redux
Redux
is a predictable state container for JavaScript applications. It helps manage
the state of your application in a single, immutable state tree, which makes it
easier to debug and test. Redux is often used with React, but it can be used
with any JavaScript framework or library.
Why Should I Use Redux?
- Predictable
State Management:
Redux maintains the state of an entire application in a single store,
making the flow of data predictable and easier to debug.
- Centralized
Store:
State is kept in a single location, so changes are easier to track and
manage.
- Debugging:
Tools like Redux DevTools provide powerful debugging capabilities.
- Consistency:
Redux helps maintain consistent data flow across the app by using actions
and reducers.
What is React-Redux?
React-Redux
is a library that helps connect React components to the Redux store. It
provides a set of utilities to integrate Redux with React seamlessly.
Key Concepts in Redux:
- Actions:
Plain JavaScript objects that represent an event or an intention to change
the state. They must have a type
property that describes the action, and can have additional payload data.
Example:
Javascript
const
ADD_TODO = 'ADD_TODO';
const
addTodo = (text) => ({
type: ADD_TODO,
payload: text,
});
- Reducers:
Functions that specify how the state changes in response to actions. They
take the current state and an action, and return a new state.
Example:
Javascript
const
todosReducer = (state = [], action) => {
switch (action.type) {
case ADD_TODO:
return [...state, action.payload];
default:
return state;
}
};
- Store:
An object that holds the state of the application. The store is created
using the createStore
function from Redux and is where you register reducers.
Example:
Javascript
import
{ createStore } from 'redux';
const
store = createStore(todosReducer);
- Dispatch:
A function that sends actions to the Redux store. Dispatching an action
causes the reducer to process it and update the state accordingly.
Example:
Javascript
store.dispatch(addTodo('Learn
Redux'));
- Connect:
A higher-order component provided by react-redux
that connects a React component to the Redux store. It lets you map state
and dispatch to the component’s props.
Example:
Javascript
import
{ connect } from 'react-redux';
const
mapStateToProps = (state) => ({
todos: state,
});
const
mapDispatchToProps = (dispatch) => ({
addTodo: (text) =>
dispatch(addTodo(text)),
});
export
default connect(mapStateToProps, mapDispatchToProps)(TodoComponent);
- Action
Types:
Constants that represent different action types. They help avoid typos and
make actions more manageable.
Example:
Javascript
export
const ADD_TODO = 'ADD_TODO';
- Action
Creators:
Functions that create actions. They help encapsulate the creation of
action objects.
Example:
Javascript
export
const addTodo = (text) => ({
type: ADD_TODO,
payload: text,
});
Redux Dependencies
- Redux:
The core library for managing state.
- React-Redux:
Provides bindings to integrate Redux with React. It includes utilities
like connect,
Provider,
and hooks like useSelector
and useDispatch.
- Redux
Thunk:
A middleware that allows you to write action creators that return a
function instead of an action. This function can perform asynchronous
operations before dispatching an action.
Example:
Javascript
const
fetchTodos = () => {
return async (dispatch) => {
const response = await fetch('/todos');
const todos = await response.json();
dispatch({ type: 'SET_TODOS', payload:
todos });
};
};
- Redux
DevTools Extension: A browser extension that
provides a way to inspect and debug Redux state and actions.
What is Provider?
Provider
is a component from react-redux
that makes the Redux store available to any nested components that need to
access it. It should be placed at the top level of your application.
Example:
Javascript
import
{ Provider } from 'react-redux';
import
{ store } from './store';
const
App = () => (
<Provider store={store}>
<TodoApp />
</Provider>
);
Extending Redux Functionality
You
can extend Redux’s functionality with middleware (like Redux Thunk for async
operations) and enhancers (like Redux DevTools). You can also use libraries
like reselect
for creating memoized selectors.
Combine More Than One Reducer
You
can use combineReducers
to combine multiple reducers into a single reducer function.
Example:
Javascript
import
{ combineReducers } from 'redux';
const
rootReducer = combineReducers({
todos: todosReducer,
visibilityFilter: visibilityFilterReducer,
});
const
store = createStore(rootReducer);
useSelector
and useDispatch
Hooks in React-Redux
- useSelector:
A hook that allows you to extract data from the Redux store state. It
takes a selector function and returns the selected state.
Example:
Javascript
import
{ useSelector } from 'react-redux';
const
TodosList = () => {
const todos = useSelector((state) =>
state.todos);
return (
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
);
};
- useDispatch:
A hook that provides a reference to the dispatch
function. It allows you to dispatch actions from within a functional
component.
Example:
Javascript
import
{ useDispatch } from 'react-redux';
const
AddTodo = () => {
const dispatch = useDispatch();
const handleClick = () => {
dispatch(addTodo('New Todo'));
};
return <button
onClick={handleClick}>Add Todo</button>;
};
Summary
- Redux
helps manage state in a predictable way with a single store.
- React-Redux
provides tools like connect,
Provider,
and hooks (useSelector,
useDispatch)
to connect React components with the Redux store.
- Actions
and reducers are central to Redux, defining how the state changes
in response to events.
- Store
is where the state lives, dispatch is used to send actions, and Provider
makes the store accessible to components.
- Redux
Thunk
enables async operations, and Redux DevTools helps with debugging.
- Use
combineReducers
to manage multiple reducers and extend functionality with middleware and
libraries.
Third-Party
Packages Implementation in React
- React
Table
Purpose:
A library for creating customizable and efficient data tables.
Installation:
Bash
npm
install react-table
Example:
Javascript
import
{ useTable } from 'react-table';
const
Table = ({ columns, data }) => {
const { getTableProps, getTableBodyProps,
headerGroups, rows, prepareRow } = useTable({ columns, data });
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr
{...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column
=> (
<th
{...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => (
<td
{...cell.getCellProps()}>{cell.render('Cell')}</td>
))}
</tr>
);
})}
</tbody>
</table>
);
};
- node-sass
Purpose:
Allows you to use SCSS syntax in your stylesheets for better organization and
modularity.
Installation:
Bash
npm
install node-sass
Usage: Rename your CSS
files to .scss
and use SCSS syntax.
Example:
Scss
//
styles.scss
$primary-color:
#3498db;
.button
{
background-color: $primary-color;
padding: 10px;
}
- sweetalert2
Purpose:
Provides beautiful and customizable alert dialogs.
Installation:
Bash
npm
install sweetalert2
Example:
Javascript
import
Swal from 'sweetalert2';
const
showAlert = () => {
Swal.fire({
title: 'Success!',
text: 'You have successfully implemented
SweetAlert2',
icon: 'success',
confirmButtonText: 'OK'
});
};
- react-tabs
Purpose:
Provides a simple way to create tabbed interfaces.
Installation:
Bash
npm
install react-tabs
Example:
Javascript
import
{ Tabs, Tab } from 'react-tabs';
import
'react-tabs/style/react-tabs.css';
const
MyTabs = () => (
<Tabs>
<TabList>
<Tab>Tab 1</Tab>
<Tab>Tab 2</Tab>
</TabList>
<TabPanel>
<h2>Content of Tab 1</h2>
</TabPanel>
<TabPanel>
<h2>Content of Tab 2</h2>
</TabPanel>
</Tabs>
);
- react-responsive-modal
Purpose:
A responsive modal component.
Installation:
Bash
npm
install react-responsive-modal
Example:
Javascript
import
{ Modal } from 'react-responsive-modal';
import
'react-responsive-modal/styles.css';
const
MyModal = ({ open, onClose }) => (
<Modal open={open} onClose={onClose}>
<h2>My Modal</h2>
</Modal>
);
- React
Feather Icons
Purpose:
Provides a collection of Feather icons for use in React.
Installation:
Bash
npm
install react-feather
Example:
Javascript
import
{ Camera, Search } from 'react-feather';
const
IconComponent = () => (
<div>
<Camera />
<Search />
</div>
);
- React-Toastify
Purpose:
Provides toast notifications for React.
Installation:
Bash
npm
install react-toastify
Example:
Javascript
import
{ ToastContainer, toast } from 'react-toastify';
import
'react-toastify/dist/ReactToastify.css';
const
notify = () => toast("Wow so easy!");
const
App = () => (
<div>
<button
onClick={notify}>Notify!</button>
<ToastContainer />
</div>
);
- React
Count To
Purpose:
Allows animated counting for numerical values.
Installation:
Bash
npm
install react-count-to
Example:
Javascript
import
CountTo from 'react-count-to';
const
CountComponent = () => (
<CountTo to={100} speed={1000} />
);
- React
Google Charts
Purpose:
Provides a wrapper for Google Charts.
Installation:
Bash
npm
install react-google-charts
Example:
Javascript
import
{ Chart } from 'react-google-charts';
const
data = [
['Year', 'Sales'],
['2013', 1000],
['2014', 1170],
['2015', 660],
['2016', 1030],
];
const
options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' },
};
const
MyChart = () => (
<Chart
chartType="LineChart"
data={data}
options={options}
width="100%"
height="400px"
legendToggle
/>
);
- react-helmet
Purpose:
Manages the document head (meta tags, title, etc.) in React applications.
Installation:
Bash
npm
install react-helmet
Example:
Javascript
import
{ Helmet } from 'react-helmet';
const
MyComponent = () => (
<div>
<Helmet>
<title>My Title</title>
<meta name="description"
content="My description" />
</Helmet>
<h1>Hello, World!</h1>
</div>
);
- react-slick
Purpose:
A carousel component for React based on Slick.
Installation:
Bash
npm
install react-slick slick-carousel
Example:
Javascript
import
Slider from 'react-slick';
import
'slick-carousel/slick/slick.css';
import
'slick-carousel/slick/slick-theme.css';
const
settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1
};
const
Carousel = () => (
<Slider {...settings}>
<div><h3>Slide
1</h3></div>
<div><h3>Slide
2</h3></div>
<div><h3>Slide
3</h3></div>
</Slider>
);
- React
Multilingual with Redux
Purpose:
Provides multilingual support in React applications using Redux for state management.
Installation:
Bash
npm
install react-redux redux react-i18next i18next
Example:
Javascript
import
i18n from 'i18next';
import
{ Provider, useDispatch } from 'react-redux';
import
{ createStore } from 'redux';
import
{ useTranslation } from 'react-i18next';
//
i18n configuration
i18n.init({
resources: {
en: {
translation: {
"welcome":
"Welcome"
}
},
fr: {
translation: {
"welcome":
"Bienvenue"
}
}
},
lng: "en",
fallbackLng: "en"
});
const
rootReducer = (state = { language: 'en' }, action) => {
switch (action.type) {
case 'SET_LANGUAGE':
return { ...state, language:
action.payload };
default:
return state;
}
};
const
store = createStore(rootReducer);
const
LanguageSwitcher = () => {
const dispatch = useDispatch();
const { t } = useTranslation();
return (
<div>
<button onClick={() => dispatch({
type: 'SET_LANGUAGE', payload: 'en' })}>English</button>
<button onClick={() => dispatch({
type: 'SET_LANGUAGE', payload: 'fr' })}>French</button>
<p>{t('welcome')}</p>
</div>
);
};
const
App = () => (
<Provider store={store}>
<LanguageSwitcher />
</Provider>
);
- react-slide-toggle
Purpose:
Provides a slide-toggle component for animations.
Installation:
Bash
npm
install react-slide-toggle
Example:
Javascript
import
SlideToggle from 'react-slide-toggle';
const
SlideComponent = () => (
<SlideToggle>
{({ toggle, setCollapsibleElement }) =>
(
<div>
<button
onClick={toggle}>Toggle</button>
<div ref={setCollapsibleElement}>
<p>Slide me!</p>
</div>
</div>
)}
</SlideToggle>
);
- React
Sticky Box
Purpose:
Provides a sticky box component that stays in place as you scroll.
Installation:
Bash
npm
install react-sticky-box
Example:
Javascript
import
StickyBox from 'react-sticky-box';
const
StickyComponent = () => (
<StickyBox>
<div style={{ height: '200px',
backgroundColor: 'lightgray' }}>
I stay sticky!
</div>
</StickyBox>
);
- react-infinite-scroll-component
Purpose:
Provides infinite scrolling functionality.
Installation:
Bash
npm
install react-infinite-scroll-component
Example:
Javascript
import
InfiniteScroll from 'react-infinite-scroll-component';
const
InfiniteComponent = () => {
const [items, setItems] =
React.useState([...Array(20).keys()]);
const fetchData = () => {
setTimeout(() => {
setItems(items.concat([...Array(20).keys()]));
}, 1000);
};
return (
<InfiniteScroll
dataLength={items.length}
next={fetchData}
hasMore={true}
loader={<h4>Loading...</h4>}
>
{items.map((item, index) => (
<div key={index}>Item
{item}</div>
))}
</InfiniteScroll>
);
};
- react-input-range
Purpose:
Provides a range slider component.
Installation:
Bash
npm
install react-input-range
Example:
Javascript
import
InputRange from 'react-input-range';
import
'react-input-range/lib/css/index.css';
const
RangeSlider = () => {
const [value, setValue] = React.useState({
min: 0, max: 100 });
return (
<InputRange
maxValue={100}
minValue={0}
value={value}
onChange={value => setValue(value)}
/>
);
};
- Stripe
Payment Gateway in React JS
Purpose:
Allows integration with the Stripe payment gateway.
Installation:
Bash
npm
install @stripe/stripe-js @stripe/react-stripe-js
Example:
Javascript
import
{ Elements, CardElement, useStripe, useElements } from
'@stripe/react-stripe-js';
import
{ loadStripe } from '@stripe/stripe-js';
const
stripePromise = loadStripe('your-public-key-here');
const
CheckoutForm = () => {
const stripe = useStripe();
const elements = useElements();
const handleSubmit = async (event) => {
event.preventDefault();
if (!stripe || !elements) return;
const { error, paymentMethod } = await
stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement),
});
if (error) {
console.error(error);
} else {
console.log(paymentMethod);
}
};
return (
<form onSubmit={handleSubmit}>
<CardElement />
<button type="submit"
disabled={!stripe}>Pay</button>
</form>
);
};
const
App = () => (
<Elements stripe={stripePromise}>
<CheckoutForm />
</Elements>
);
Summary
- React
Table:
Efficient data tables.
- node-sass:
SCSS support in stylesheets.
- sweetalert2:
Customizable alerts.
- react-tabs:
Tabbed interfaces.
- react-responsive-modal:
Responsive modals.
- React
Feather Icons:
Feather icons for React.
- React-Toastify:
Toast notifications.
- React
Count To:
Animated numerical counts.
- React
Google Charts:
Google Charts integration.
- react-helmet:
Manage document head.
- react-slick:
Carousel component.
- React
Multilingual with Redux: Multilingual
support with Redux.
- react-slide-toggle:
Slide-toggle animations.
- React
Sticky Box:
Sticky box component.
- react-infinite-scroll-component:
Infinite scrolling.
- react-input-range:
Range sliders.
- Stripe
Payment Gateway:
Stripe integration for payments.
Overview of JSON Web Tokens (JWT)
JSON
Web Tokens (JWT)
are a compact, URL-safe means of representing claims to be transferred between
two parties. The claims in a JWT are encoded as a JSON object that is used as a
payload of a JSON Web Signature (JWS) structure or as a JSON Web Encryption
(JWE) structure, enabling the claims to be digitally signed or integrity
protected with a Message Authentication Code (MAC) and/or encrypted.
JSON Web
Tokens
Structure: A JWT consists of
three parts, separated by dots (.
):
1.
Header: Contains metadata
about the token. Typically, this includes the type of token (JWT) and the
signing algorithm used (e.g., HMAC SHA256 or RSA).
2.
Payload: Contains the claims,
which are statements about an entity (typically, the user) and additional data.
Claims are of three types: registered, public, and private.
3.
Signature: Used to verify that
the token hasn’t been altered. It’s created by taking the encoded header and
payload, a secret key, and applying the algorithm specified in the header.
Example
JWT:
eyJhbGciOiAiSFMyNTYiLCAic3RhdHVzIjogIkNPTVAtU1BBIn0.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsICJuYW1lIjogIkpvaG4gRG9lIiwgImVtYWlsIjogImpvaG5AZG9lLmNvbSJ9.X4i66zS78YPL17dyzFWuUJmh9cGSbyD0b6LkftC_7rI
How JWT
Tokens Are Used
JWTs are
commonly used in authentication and authorization. Here’s how they typically
work:
1.
Authentication: After a user logs in
with their credentials, the server generates a JWT and sends it to the client.
The client then includes this token in the Authorization
header of subsequent
requests. The server validates the token and processes the request accordingly.
2.
Authorization: JWTs can also be used
to grant access to resources. For instance, a JWT might include claims about a
user’s roles or permissions, which the server uses to determine if the user can
access certain resources or perform specific actions.
Example:
1.
User
logs in:
- Client sends a
login request with username and password.
- Server validates
the credentials and generates a JWT.
2.
Client
receives the JWT:
- JWT is stored in
the client’s local storage or cookies.
3.
Client
makes an authenticated request:
- Client includes
the JWT in the
Authorization
header of the request.
Http
GET /api/user-profile
Authorization: Bearer <token>
4.
Server
validates the JWT:
- Server extracts
the JWT from the
Authorization
header. - Server verifies
the token’s signature and checks the claims.
5.
Server
responds based on JWT validation:
- If valid, the
server processes the request.
- If invalid, the
server responds with an authentication error.
Adding JWT
to HTTP Header
To send a JWT
with an HTTP request, it is typically included in the Authorization
header. The format is:
Http
Authorization: Bearer <token>
Example:
Javascript
fetch(
'https://api.example.com/user-profile', {
method:
'GET',
headers: {
'Authorization':
`Bearer ${token}`,
// Adding JWT to HTTP Header
'Content-Type':
'application/json',
},
})
.
then(
response => response.
json())
.
then(
data =>
console.
log(data));
How The
Server Makes Use of JWT Tokens
1.
Token
Extraction:
The server extracts the JWT from the Authorization
header of the incoming
request.
2.
Token
Verification:
The server verifies the token’s signature using the secret key (for HMAC) or
public key (for RSA). This ensures the token is valid and hasn’t been tampered
with.
3.
Token
Decoding:
If the token is valid, the server decodes the payload to access the claims. The
server can use these claims to determine the user’s identity and permissions.
4.
Access
Control:
Based on the claims, the server decides whether to grant or deny access to the
requested resource.
Example:
Server-side
Implementation
(Node.js with Express and jsonwebtoken
library):
Javascript
const express =
require(
'express');
const jwt =
require(
'jsonwebtoken');
const app =
express();
const
SECRET_KEY =
'your-very-secret-key';
// Middleware to verify JWT
const
authenticateToken = (
req, res, next) => {
const authHeader = req.
headers[
'authorization'];
const token = authHeader && authHeader.
split(
' ')[
1];
if (token ==
null)
return res.
sendStatus(
401);
jwt.
verify(token,
SECRET_KEY,
(err, user) => {
if (err)
return res.
sendStatus(
403);
req.
user = user;
next();
});
};
// Protected route
app.
get(
'/user-profile', authenticateToken,
(req, res) => {
res.
json({
message:
'This is your profile data.',
user: req.
user });
});
app.
listen(
3000);
Summary
- JWT (JSON Web Tokens): Compact and
URL-safe tokens used for securely transmitting information between
parties.
- Usage: Commonly used for
authentication and authorization, allowing secure and stateless user
sessions.
- HTTP Header: JWT is added to requests
in the
Authorization
header using theBearer
schema. - Server Handling: The server
extracts the token, verifies its signature, decodes the payload, and uses
the claims for access control.
No comments:
Post a Comment