0% found this document useful (0 votes)
3 views

React Components

The document provides an overview of React components, including functional and class components, their key features like props, state, and lifecycle methods. It also discusses the Issue Tracker application, which is a CRUD application for managing issues, along with routing, middleware, and REST APIs. Additionally, it covers MongoDB's structure, features, and query language, emphasizing its document-oriented approach and flexibility.

Uploaded by

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

React Components

The document provides an overview of React components, including functional and class components, their key features like props, state, and lifecycle methods. It also discusses the Issue Tracker application, which is a CRUD application for managing issues, along with routing, middleware, and REST APIs. Additionally, it covers MongoDB's structure, features, and query language, emphasizing its document-oriented approach and flexibility.

Uploaded by

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

REACT COMPONENTS

• React components are the building blocks of a React application. They are reusable
pieces of code that define how a portion of the user interface should appear and
behave.
• There are two main types of components in React:
• 1. Functional Components: Functional components are simple JavaScript functions
that return JSX. They are often used for presentational purposes.
• Example: function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;}
• 2. Class Components: Class components are more complex and are defined using
ES6 classes. They can hold their own state and lifecycle methods.
• Example: class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
KEY FEATUERS:
• Props: Components can receive input via props (properties), allowing them to be
reusable with different data.
• State: Class components can manage their own state, allowing them to respond to
user input and changes in data.
• Lifecycle Methods: Class components have lifecycle methods (like
componentDidMount, componentDidUpdate, and componentWillUnmount) that let
you run code at specific points in a component’s life.
• Hooks: Functional components can use hooks (like useState, useEffect) to manage
state and side effects.
• Characteristics of React Components
• 1. Reusability: React components are designed to be reusable, making it easy to
build complex UIs from smaller, reusable pieces.
• 2. Encapsulation: React components encapsulate their own state and behavior,
making it easy to manage complexity.
• 3. Composition: React components can be composed together to form more
complex UIs.
ISSUE TRACKER
• These applications help you create a bunch of issues or bugs, assign them to people,
and track their statuses. The Issue Tracker application aims to provide a simple and
efficient way to manage issues or bugs
• These are essentially CRUD applications (Create, Read, Update, and Delete a record
in a database) that manage a list of objects or entities.
• The CRUD pattern is so useful because pretty much all enterprise applications are
built around the CRUD pattern on different entities or objects.
• In the case of the Issue Tracker, we’ll only deal with a single object or record,
because that’s good enough to depict the pattern.
• Once you grasp the fundamentals of how to implement the CRUD pattern in MERN,
you’ll be able to replicate the pattern and create a real-life application.
Here’s the requirement list for the Issue Tracker application, a simplified or toned-down
version of GitHub Issues or Jira:
• The Issue Tracker application should provide the following features:
• 1. View Issue List: Display a list of all issues, with filtering options by various
parameters.
• 2. Add New Issue: Allow users to create new issues by providing initial values for the
issue's fields.
• 3. Edit and Update Issue: Enable users to edit and update existing issues by changing
their field values.
• 4. Delete Issue: Allow users to delete existing issues.
An issue should have following attributes:
• A title that summarizes the issue (freeform long text)
• An owner to whom the issue is assigned (freeform short text)
• A status indicator (a list of possible status values)
• Creation date (a date, automatically assigned)
• Effort required to address the issue (number of days, a number)
• Estimated completion date or due date (a date, optional)

REACT CLASSES

• React classes are used to create real components.


• These classes can then be reused within other components, handle events, and so
much more.
• To start with, let’s replace the Hello World example with a simple class forming the
starting point for the Issue Tracker application.
• React classes are created by extending React.Component, the base class from which
all custom classes must be derived.
• Within the class definition, at the minimum, a render() method is needed.
• This method is what React calls when it needs to display the component in the UI.
• Hello World example from a simple element to use a React class called HelloWorld,
extended from React.Component:
...
class HelloWorld extends React.Component {
...
}
...
• within this class, a render() method is needed, which should return an element. We’ll
use the same JSX <div> with the message as the returned element.
...
render() {
return (
<div title="Outer div">
<h1>{message}</h1>
</div>
);
...
• Move all the code for message construction to within the render() function so that it
remains encapsulated within the scope where it is needed rather than polluting the
global namespace.
...
render() {
const continents = ['Africa','America','Asia','Australia','Europe'];
const helloContinents = Array.from(continents, c => `Hello ${c}!`);
const message = helloContinents.join(' ');
return (
...
);
...
REACT CLASS AND INSTANCE
• class HelloWorld extends React.Component {
• render() {
• const continents = ['Africa','America','Asia','Australia','Europe'];
• const helloContinents = Array.from(continents, c => `Hello ${c}!`);
• const message = helloContinents.join(' ');
• return (
• <div title="Outer div">
• <h1>{message}</h1>
• </div>
• );
• }
• }
• const element = <HelloWorld />;
• ReactDOM.render(element, document.getElementById('contents'));

EVENT HANDLING

• ...
• <div>This is a placeholder for a form to add an issue.</div>
• <form>
• <input type="text" name="owner" placeholder="Owner" />
• <input type="text" name="title" placeholder="Title" />
• <button>Add</button>
• </form>
• ...
• At this point, we can remove the timer that creates an issue from the constructor.
• ...
• constructor() {
• super();
• setTimeout(() => {
• this.props.createIssue(sampleIssue);
• }, 2000);
• }
• ...
ROUTING
• Routing in Express.js refers to how an application responds to client requests (such
as GET, POST, PUT, DELETE) to specific endpoints (URLs).
• With Express, defining routes is very easy and flexible. Routes map HTTP requests to
specific functions, which is crucial for building APIs and web pages.
KEY CONCEPTS
• Route Definition: A route defines the URL and HTTP method (e.g., GET, POST) that
an application will listen for and respond to.
• Route Handlers: The functions that execute when a route is matched. These
functions can send back responses, interact with databases, perform business logic,
etc.
• Route Parameters: Dynamic placeholders in a URL that can capture values, like user
IDs or product names.
• Query Parameters: Parameters appended to the URL, typically after a ?, that are
used to pass data in a URL.
BASIC SYNTAX:
• To define a route in Express, we use app.METHOD() where METHOD is the HTTP
method (such as get, post, put, or delete), and the first argument is the path.
• app.get('/home', (req, res) => {
• res.send('Welcome to the Home Page!');
• });
• app.get(): This defines a route that listens for GET requests.
• /home: The URL or path the route is associated with.
MIDDLEWARE
• Middleware functions are an essential concept that enables the processing of
requests and responses in the application pipeline.
• Middleware functions are functions that have access to the request object (req), the
response object (res), and the next middleware function in the application's request-
response cycle.
• Middleware functions are executed sequentially in the order they are defined.
• Middleware can end the request-response cycle by sending a response or call next()
to pass control to the next middleware.
Application-Level Middleware
• These are bound to an instance of the Express application using app.use() or specific
HTTP methods like app.get() or app.post().
Router-Level Middleware
• These work similarly to application-level middleware but are specific to an instance
of express.Router().
Error-Handling Middleware
• Error-handling middleware must have four arguments: (err, req, res, next).

APPLICATION LEVEL MIDDLEWARE


const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Request URL:', req.url);
next(); // Pass control to the next middleware
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => console.log('Server running on port 3000'));

ROUTER LEVEL MIDDLEWARE


• const express = require('express');
• const app = express();
• const router = express.Router();
• router.use((req, res, next) => {
• console.log('Router-level middleware executed.');
• next();
• });
• router.get('/', (req, res) => {
• res.send('Router Middleware Example');
• });
• app.use('/router', router);
• app.listen(3000, () => console.log('Server running on port 3000'));

ERROR-HANDLING MIDDLEWARE
app.use((err, req, res, next) => {
• console.error(err.stack);
• res.status(500).send('Something broke!');
• });

REST API
• REST API (Representational State Transfer Application Programming Interface) is a
set of rules and conventions for building and interacting with web services.
• REST is an architectural style that allows systems to communicate using stateless,
client-server protocols, primarily HTTP.
• REST APIs are widely used for creating scalable, maintainable, and flexible web
services.
Although the HTTP method and operation mapping are well mapped and specified, REST by
itself lays down no rules for the following:
• Filtering, sorting, and paginating a list of objects. The query string is commonly used
in an implementation-specific way to specify these.
• Specifying which fields to return in a READ operation.
• If there are embedded objects, specifying which of those to expand in a READ
operation.
• Specifying which fields to modify in a PATCH operation.
• Representation of objects. You are free to use JSON, XML, or any other
representation for the objects in both READ and WRITE operations.

BENEFITS OVER REST

GRAPHQL
What is GraphQL?

• A query language for APIs.


• Runtime for executing those queries.
• Developed by Facebook in 2015.
• Focus on flexibility and efficiency.
• Key feature: Fetch only the data you need.
COMPONENTS
• Frontend: Query data via a GraphQL client (e.g., Apollo Client, Relay).
• Backend: Serve data with a GraphQL API (e.g., Apollo Server, GraphQL Yoga).
• Database: Store and manage data (e.g., MongoDB, PostgreSQL).
• Middleware: Handle authentication, authorization, and data transformation.
FRONTEND IMPLEMENTATION
• Tools:
• Apollo Client: Simplifies state management and data fetching.
• Relay: Highly optimized for large-scale applications.
• Features:
• Query composition.
• Optimistic UI updates.
• Caching for performance.
• Code Example: Simple query example in JavaScript/React.
BACKEND IMPLEMENTATION
• Tools:
• Apollo Server: GraphQL server framework.
• Express.js for middleware integration.
• Features:
• Schema definition: Types, Queries, Mutations.
• Resolvers for business logic.
• Real-time with Subscriptions (WebSockets).
• Code Example: Sample resolver and schema.
TOOLS AND BEST PRACTICES
• Schema-First Development: Define schema before coding.
• Error Handling: Standardize error responses.
• Performance: Use DataLoader for batching and caching.
• Security:
• Use depth/complexity limiting tools.
• Secure authentication and authorization.
• Versioning: Maintain compatibility.
CHALLENGES
• Overhead in learning curve.
• Complexity in schema design for large teams.
• Managing real-time data at scale.

CALL BACKS AND EVENTS IN NODE.JS


• A callback is a function passed into another function as an argument to be executed
later.
• // Simple callback example
• function greet(name, callback) {
console.log("Hello " + name);
callback();
}
greet("Alice", function() {
console.log("Callback function executed");
});
• Event-driven architecture: The EventEmitter class allows objects to emit events and
register listeners.
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
// Listener for an event
eventEmitter.on('greet', function() {
console.log("Hello, Event-driven World!");
});
// Emitting the event
eventEmitter.emit('greet');
MONGODB
• MongoDB is a popular NoSQL database.
• It stores data in a document-oriented format using JSON-like documents called BSON
(Binary JSON).
• Highly scalable, flexible, and well-suited for handling large amounts of unstructured
or semi-structured data.
• Unlike traditional relational databases (SQL), MongoDB does not use tables and
rows.
KEY FEATURES
• Document-Oriented: Data stored in documents (BSON format).
• Scalability: Horizontal scaling via sharding.
• Flexible Schema: No fixed schema for documents.
• High Availability: Built-in replication for fault tolerance.
• Rich Query Language: Supports complex queries, indexing, and aggregation.
ARCHITECTURE
• Database: Contains collections of documents.
• Collection: Group of documents (equivalent to a table in SQL).
• Document: Individual record stored in BSON format (equivalent to a row in SQL).
• Field: Key-value pairs inside documents (similar to columns in SQL).
• Replica Set: Provides high availability through data replication.
• Sharding: Distributes data across multiple servers for horizontal scalability.
DATABASE
• A database in MongoDB is a container for collections.
• Multiple databases can exist within a single MongoDB instance.
• Each database has its own collections and indexes.
• Example:
• db1: Stores user data (users collection).
• db2: Stores order data (orders collection).
MONGODB COILLECTIONS
• Collection:
• A group of MongoDB documents.
• Collections are analogous to tables in relational databases, but unlike tables,
collections do not require a fixed schema.
• Document:
• A set of key-value pairs (fields), stored as BSON.
• Documents in a collection can have different fields.
• //json code
{
"_id": 1,
"name": "John Doe",
"age": 30,
"email": "[email protected]"
}
//json code
{
"_id": 1,
"name": "John Doe",
"age": 30,
"email": "[email protected]"
}
MONGODB DOCUMENTS
• A document is the basic unit of data in MongoDB.
• Stored as a BSON (Binary JSON) format.
• Unlike SQL rows, documents are flexible, meaning each document in a collection can
have different fields and data types.
• {
"_id": 123,
"name": "Alice",
"age": 25,
"address": {
"street": "123 Main St",
"city": "New York"
}
}
MONGODB QUERY LANGUAGE
• MongoDB provides a rich query language to interact with the data.
• Supports operations like find, insert, update, delete, and more.
• MongoDB queries are structured in JSON-like syntax.
• Find: db.users.find({ "age": 30 });
• Insert: db.users.insertOne({ "name": "John", "age": 30 });
• Update: db.users.updateOne({ "name": "John" }, { $set: { "age": 31 } });
• Delete: db.users.deleteOne({ "name": "John" });
AGGREGATION FRAMEWORK
• Allows for more advanced data processing.
• Performs operations such as filtering, grouping, sorting, and transforming data.
• Example: Group users by age and count the number of users in each age group
• db.users.aggregate([
{ $group: { _id: "$age", count: { $sum: 1 } } }
]);
MONGOSHELL
• The Mongo Shell is an interactive JavaScript interface for MongoDB.
• It allows users to interact with MongoDB through commands and queries.
• Can be used for administration, querying, and data manipulation.
• Start: mongod
• Connect to MongoDB: mongo
• Show all databases: show dbs;
• Switch to a specific database: use myDatabase;
MONGODB INDEXES
• Indexes: Improve query performance by reducing the number of documents to scan.
• Supports various types of indexes:
Single Field Indexes
Compound Indexes
Geospatial Indexes
• Text Indexes
• MongoDB supports replication through Replica Sets.
• A Replica Set is a group of MongoDB servers that maintain the same data set.
• Provides high availability and data redundancy.
• If the primary server fails, one of the secondary servers automatically becomes the
• primary.
MONGODB DATA REPLICATION
• MongoDB supports replication through Replica Sets.
• A Replica Set is a group of MongoDB servers that maintain the same data set.
• Provides high availability and data redundancy.
• If the primary server fails, one of the secondary servers automatically becomes the
primary.
MONGODB SHARDING
• Sharding is MongoDB’s approach to horizontal scaling.
• It distributes data across multiple machines (shards) to handle large datasets and
high throughput.
• Helps improve performance and scalability for large applications.
MONGODB USECASES
• Content Management: Store dynamic content like blog posts, comments, and media
files.
• Real-Time Analytics: Process and analyze large-scale, real-time data.
• Mobile & IoT Applications: Store unstructured data for mobile apps and IoT devices.
• E-commerce: Manage product catalogs, user profiles, and order histories.

You might also like