0% found this document useful (0 votes)
50 views30 pages

React Component Lifecycle Demo

The document outlines various exercises demonstrating React components, Redux applications, React routing, and Node.js file handling. Each exercise includes code snippets for creating a React component lifecycle demo, a calculator app, a Redux counter, a routing website, and Node.js applications for data I/O and file system access. The document serves as a comprehensive guide for practical implementations of these technologies.

Uploaded by

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

React Component Lifecycle Demo

The document outlines various exercises demonstrating React components, Redux applications, React routing, and Node.js file handling. Each exercise includes code snippets for creating a React component lifecycle demo, a calculator app, a Redux counter, a routing website, and Node.js applications for data I/O and file system access. The document serves as a comprehensive guide for practical implementations of these technologies.

Uploaded by

22501a12a4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXERCISE – 1

AIM: Demonstrate React Component Life cycle

[Link]
import React, { Component } from 'react';
import { render } from 'react-dom';

class LifeCycleDemoComponent extends Component {


constructor(props) {
super(props);
}

componentDidMount() {
[Link]('componentDidMount');
}

componentDidUpdate() {
[Link]('componentDidUpdate');
}

componentWillUnmount() {
[Link]('componentWillUnmount');
}

render() {
return <p>{[Link]}</p>
}
}

class App extends Component {


constructor() {
super();
[Link] = {
num: 0,
show: false
}
}

render() {
return (
<>
<button onClick={() => [Link]({ num: [Link] + 1 })}>Add One</button>
<button onClick={() => [Link]({show: ![Link]})}>Toggle</button>
{[Link] && <LifeCycleDemoComponent num={[Link]} />}
</>);
}
}

render(<App />, [Link]('root'));

Output:
EXERCISE - 2

AIM: Develop a Calculator React Application

[Link]
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

const rootElement = [Link]("root");


[Link](
<App />,
rootElement
);

[Link]
import React, { Component } from 'react';
import './[Link]';
import ResultComponent from './components/ResultComponent';
import KeyPadComponent from './components/KeyPadComponent';

class App extends Component {


state = {
result: ""
}

onClick = button => {


if(button === "=") {
[Link]();
}

else if(button === "C") {


[Link]();
}

else if(button === "del") {


[Link]();
}

else {
[Link]({
result: [Link] + button
})
}
};

calculate = () => {
var checkResult = ''
checkResult = [Link];

try {
[Link]({
result: (eval(checkResult)) })
}
catch(e) {
[Link]({
result: "error"
})
}
};

reset = () => {
[Link]({
result: ""
})
};

backspace = () => {
[Link]({
result: [Link](0, -1)
})
};

render() {
return (
<div>
<div className="calculator-body">
<h1>Simple Calculator</h1>
<ResultComponent result={[Link]} />
<KeyPadComponent onClick={[Link]} />
</div>
</div>
)
}
}

export default App;


[Link]
import React, { Component } from 'react';

class ResultComponent extends Component {


render() {
let { result } = [Link];
return (
<div className="result">
<p>{ result }</p>
</div>
)
}
}
export default ResultComponent;

[Link]
import React, { Component } from 'react';

class KeyPadComponent extends Component {


render() {
return (
<div className="button">

<button name="(" onClick={e => [Link]([Link])}>(</button>


<button name="del" onClick={e => [Link]([Link])}>CE</button>
<button name=")" onClick={e => [Link]([Link])}>)</button>
<button name="C"onClick={e=>[Link]([Link])}>C</button><br/>

<button name="1" onClick={e => [Link]([Link])}>1</button>


<button name="2" onClick={e => [Link]([Link])}>2</button>
<button name="3" onClick={e => [Link]([Link])}>3</button>
<button name="+" onClick={e => [Link]("+")}>+</button><br/>

<button name="4" onClick={e => [Link]([Link])}>4</button>


<button name="5" onClick={e => [Link]([Link])}>5</button>
<button name="6" onClick={e => [Link]([Link])}>6</button>
<button name="-" onClick={e => [Link]([Link])}>-</button><br/>

<button name="7" onClick={e => [Link]([Link])}>7</button>


<button name="8" onClick={e => [Link]([Link])}>8</button>
<button name="9" onClick={e => [Link]([Link])}>9</button>
<button name="*" onClick={e =>[Link]([Link])}>x</button><br/>

<button name="." onClick={e => [Link]([Link])}>.</button>


<button name="0" onClick={e => [Link]([Link])}>0</button>
<button name="=" onClick={e => [Link]([Link])}>=</button>
<button name="/" onClick={e =>[Link]([Link])}>÷</button><br/>
</div>
)
}
}
export default KeyPadComponent;

Output:
EXERCISE-3

AIM: Develop a Redux application

[Link]
import React from "react";
import {createRoot} from 'react-dom/client';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './App';

const initialState = {
count: 0
};

function reducer(state = initialState, action) {


switch([Link])
{
case 'INCREMENT': return { count: [Link] + 1 };
case 'DECREMENT': return { count: [Link] - 1 };
default: return state;
}
}

const store = createStore(reducer);


const root = createRoot([Link]('root'));
[Link](<Provider store={store}>
<App />
</Provider>);

[Link]
import React from 'react';
import { connect } from 'react-redux';

function Counter(props) {
return (
<div>
<h1>Counter: {[Link]}</h1>
<button onClick={[Link]}>Increment</button>
<button onClick={[Link]}>Decrement</button>
</div>
);
}
function mapStateToProps(state) {
return {
count: [Link] };
}

function mapDispatchToProps(dispatch) {
return {
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }) };
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

Output:
EXERCISE - 4

AIM: Develop Website demonstrate React Routing

[Link]
import React from 'react';
import { Link, Outlet} from 'react-router-dom';
const Header = () => { return (<nav>
<Link to="home">Home</Link>
<Link to="about"> About Us </Link>
<Link to="contact"> Contact Us </Link>
<Outlet/>
</nav>)
}
export default Header;

[Link]
const About = () => {
return <>
<h2> Inside About Us</h2>
</>
}
export default About;

[Link]
const ContactUs = () => {
return <>
<h2> Inside ContactUs</h2>
</>
}
export default ContactUs;

[Link]
const Home = () => {
return <>
<h2> Inside home</h2>
</>
}
export default Home;

[Link]
import React from 'react';
import ReactDOM from 'react-dom/client';
import {BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Header from './components/Header'; import Home from
'./components/Home'; import About from './components/About';
import ContactUs from './components/Contact';

class RoutingDemo extends [Link]{


render(){ return( <Router>
<Routes>
<Route path="/" element={<Header />}>
<Route index element={<Home />}/>
<Route path="home" element={<Home />}/>
<Route path="about" element={<About />}/>
<Route path="contact" element={<ContactUs />}/>
</Route>
</Routes>
</Router>
)
}
}
const root = [Link]([Link]('root'));
[Link](
<RoutingDemo />
);

Output:
EXERCISE-5
Aim: Develop a [Link] application demonstrating handling data I/O (Buffer,
Stream, Zlib modules)
[Link]
buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97;
}
[Link]( [Link]('ascii'));
[Link]( [Link]('ascii',0,5));
[Link]( [Link]('utf8',0,5));
[Link]( [Link](undefined,0,5));
var buffer1 = new Buffer('Tutorials Point ');
var buffer2 = new Buffer('Simply Easy Learning');
var buffer3 = [Link]([buffer1,buffer2]);
[Link]("concatenated content: " + [Link]());
var b1 = [Link](0,9);
[Link]("sliced content: " + [Link]());
[Link]("buffer length: " + [Link]);
var json = [Link](buffer2);
[Link](json);
OUTPUT:
Streams:
[Link]
var fs = require('fs');
var grains = ['wheat', 'rice', 'oats'];
var options = { encoding: 'utf8', flag: 'w' };
var fileWriteStream = [Link]("[Link]", options);
[Link]("close", function(){
[Link]("File Closed.");
});
while ([Link]){
var data = [Link]() + " ";
[Link](data);
[Link]("Wrote: %s", data);
}
[Link]();
var options = { encoding: 'utf8', flag: 'r' };
var fileReadStream = [Link]("[Link]", options);
[Link]('data', function(chunk) {
[Link]('Grains: %s', chunk);
[Link]('Read %d bytes of data.', [Link]);
});
OUTPUT :
vowels_count.js
const fs = require('fs');
function countChars(filename) {
const vowels = 'aeiouAEIOU';
let vowelCount = 0;
let consonantCount = 0;
let digitCount = 0;
let specialCharCount = 0;
const stream = [Link](filename, { encoding: 'utf8' });
[Link]('data', (data) => {
for (const char of data) {
if ([Link](/[a-zA-Z]/)) {
if ([Link](char)) {
vowelCount++;
} else {
consonantCount++;
}
} else if ([Link](/\d/)) {
digitCount++;
} else if ([Link](/\S/)) {
specialCharCount++;
}
}
});
[Link]('end', () => {
[Link](`Vowels: ${vowelCount}`);
[Link](`Consonants: ${consonantCount}`);
[Link](`Digits: ${digitCount}`);
[Link](`Special Characters: ${specialCharCount}`);
});
[Link]('error', (err) => {
[Link](`Error reading file: ${err}`);
});
}

//reading file from user


const file = [Link][2];
if (file) {
countChars(file);
} else {
[Link]('Please provide a file name as an argument.');
}
OUTPUT :

[Link]
const fs = require('fs');
const countLinesWordsChars = (file) => {
let lines = 0;
let words = 0;
let chars = 0;
const stream = [Link](file, { encoding: 'utf8' });
[Link]('data', (data) => {
lines += [Link]('\n').length;
words += [Link](/\s+/).filter(Boolean).length;
chars += [Link];
});
[Link]('end', () => {
[Link](`Number of lines: ${lines}`);
[Link](`Number of words: ${words}`);
[Link](`Number of characters: ${chars}`);
});
[Link]('error', (err) => {
[Link](`Error reading file: ${err}`);
});
};
countLinesWordsChars('[Link]');
OUTPUT :

[Link]
var fs = require("fs");
// Create a readable stream
var readerStream = [Link]('[Link]');
// Create a writable stream
var writerStream = [Link]('[Link]');
// Pipe the read and write operations
// read [Link] and write data to [Link]
[Link](writerStream);
[Link]("Program Ended");
OUTPUT :
[Link]
var fs = require("fs");
var zlib = require('zlib');

// Compress the file [Link] to [Link]


[Link]('[Link]')
.pipe([Link]())
.pipe([Link]('[Link]'));
[Link]("File Compressed.");

[Link]('[Link]')
.pipe([Link]())
.pipe([Link]('[Link]'));
[Link]("File Decompressed.");

OUTPUT :
EXERCISE – 6
Aim: Demonstrate accessing File system from [Link] application
[Link]
var fs = require("fs");
[Link]("Going to get file info!");
[Link]('[Link]', function (err, stats) {
if (err) { return [Link](err); }
[Link](stats);
[Link]("Got file info successfully!");
[Link]("isFile ? " + [Link]());
[Link]("isDirectory ? " + [Link]());
});
OUTPUT :

[Link]
var fs = require('fs');
var veggieTray = ['carrots', 'celery', 'olives'];
fd = [Link]('[Link]', 'w');
while ([Link]){
veggie = [Link]() + " ";
var bytes = [Link](fd, veggie, null, null);
[Link]("Wrote %s %dbytes", veggie, bytes);
}
[Link](fd);
fd = [Link]('[Link]', 'r');
var veggies = "";
do {
var buf = new Buffer(5);
[Link]();
var bytes = [Link](fd, buf, null, 5);
[Link]("read %dbytes", bytes);
veggies += [Link]();
} while (bytes > 0);
[Link](fd);
[Link]("Veg g (to get output shown) ies: " + veggies);
OUTPUT :

[Link]
var fs = require('fs');
var fac = {
Name: "chp",
Branch: "IT",
Experience: 10
};
var configTxt = [Link](fac);
var options = {encoding:'utf8', flag:'w'};
[Link]('[Link]', configTxt, options,
function(err){
if (err){
[Link]("Faculty details Write Failed.");
} else {
[Link]("Faculty details Saved.");
}} );
options = {encoding:'utf8', flag:'r'};
[Link]('[Link]', options, function(err, data){
if (err){
[Link]("Failed to open Faculty File.");
} else {
[Link]("Faculty details:");
var fac = [Link](data);
[Link]("Name: " + [Link]);
[Link]("Branch: " + [Link]);
[Link]("Experience: " + [Link]);

}
});
OUTPUT:

[Link]
var fs = require('fs');
var Path = require('path');
function WalkDirs(dirPath){
[Link](dirPath);
[Link](dirPath, function(err, entries){
for (var idx in entries){
var fullPath = [Link](dirPath, entries[idx]);
(function(fullPath){
[Link](fullPath, function (err, stats){
if ([Link]()){
[Link](fullPath);
} else if ([Link]()){
WalkDirs(fullPath); }
});
})(fullPath);}
});
}

WalkDirs("../Files");
OUTPUT:
file_stats.js
var fs = require('fs');
[Link]('file_stats.js', function (err, stats) {
if (!err){
[Link]('stats: ' + [Link](stats, null, ' '));
[Link]([Link]() ? "Is a File" : "Is not a File");
[Link]([Link]() ? "Is a Folder" : "Is not a Folder");
[Link]([Link]() ? "Is a Socket" : "Is not a Socket");
[Link]();
[Link]();
[Link]();
//[Link](); //only lstat
[Link]();
[Link]();
}
});
OUTPUT:

[Link]
var stream = require('stream');
var util = require('util');
[Link](Duplexer, [Link]);
function Duplexer(opt) {
[Link](this, opt);
[Link] = [];
}
[Link]._read = function readItem(size) {
var chunk = [Link]();
if (chunk == "stop"){
[Link](null);
} else {
if(chunk){
[Link](chunk);
} else {
setTimeout([Link](this), 500, size);}} };
[Link]._write = function(data, encoding, callback) {
[Link](data);
callback();};
var d = new Duplexer();
[Link]('data', function(chunk){
[Link]('read: ', [Link]()); });
[Link]('end', function(){
[Link]('Message Complete');
});
[Link]("I think, ");
[Link]("therefore ");
[Link]("I am.");
[Link]("Rene Descartes");
[Link]("stop");
OUTPUT:
EXERCISE - 7
Aim : Demonstrate Express Routing.
basic_express.js
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]('Welcome to Express js!');
});
var server = [Link](8000, function () {
var host = [Link]().address;
var port = [Link]().port;
[Link]('Example app listening at [Link] host, port);
});
OUTPUT :

routing_example.js
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]("Got a GET request for the homepage");
[Link]('Welcome to Express js routing !');
})
[Link]('/enrolled_student', function (req, res) {
[Link]("Got a GET request for /enrolled_student");
[Link]('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
[Link]('/ab*cd', function(req, res) {
[Link]("Got a GET request for /ab*cd");
[Link]('Pattern Matched.');
})
var server = [Link](8000, function () {
var host = [Link]().address
var port = [Link]().port
[Link]("Example app listening at [Link] host, port)
})
OUTPUT :

route_params.js
const express = require('express');
const app = express();
const users = [ { id: 1, name: 'Gr' },{ id: 2, name: 'vr' },{ id: 3, name: 'pnr' }, ];
[Link]('/users/:id', (req, res) => {
const id = parseInt([Link]);
const user = [Link](user => [Link] === id);
if (!user) {
return [Link](404).send('User not found');
}
return [Link](user);
});
[Link](3000, () => {
[Link]('Server started on port 3000');
});
OUTPUT:
EXERCISE – 8
Aim : Demonstrate [Link] Authentication
basic_auth.js
const express = require('express');
const app = express();
const basicAuth = require('express-basic-auth');
const auth = basicAuth({
users: { 'testuser': 'tes' },
challenge: true });
[Link]('/library', (req, res) => {
[Link]('Welcome to the library.');
});
[Link]('/restricted', auth, (req, res) => {
[Link]('Welcome to the restricted section.');
});
[Link](80, () => {
[Link]('Server running on port 3000');
});
OUTPUT :
Page_auth.js
var express = require('express');
var crypto = require('crypto');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
function hashPW(pwd) {
return [Link]('sha256').update(pwd).digest('base64').toString();
}
var app = express();
[Link]([Link]({ extended: true }));
[Link](cookieParser('MAGICString'));
[Link](session({
secret: 'MAGICString',
resave: true,
saveUninitialized: true
}));
[Link]('/restricted', function(req, res) {
if ([Link]) {
[Link]('<h2>' + [Link] + '</h2>' +
'<p>You have Entered the restricted section<p><br>' +
' <a href="/logout">logout</a>'); }
else {
[Link] = 'Access denied!';
[Link]('/login'); } });
[Link]('/logout', function(req, res) {
[Link](function() {
[Link]('/login'); });
});
[Link]('/login', function(req, res) {
var response = '<form method="POST">' +'Username: <input type="text"
name="username"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Submit"></form>';
if ([Link]) {
[Link]('/restricted');}
else if ([Link]) {
response += '<h2>' + [Link] + '<h2>'; }
[Link]('html');
[Link](response);
});
[Link]('/login', function(req, res) {
var user = { name: [Link], password: hashPW('myPass') };
if ([Link] === hashPW([Link]())) {
[Link](function() {
[Link] = user;
[Link] = 'Authenticated as ' + [Link];
[Link]('/restricted'); }); }
else {
[Link](function() {
[Link] = 'Authentication failed.';
[Link]('/restricted'); });
[Link]('/login'); }
});
[Link](80);
OUTPUT:
EXERCISE – 9
Aim: Demonstrate Manipulating MongoDB Documents from [Link]
[Link]
const { MongoClient } = require('mongodb');
const uri = 'mongodb://[Link]:27017'
[Link]("Before connecting to database");
[Link](uri)
.then(client => { [Link]("Connected to database!");
[Link]("Database name:", [Link]().databaseName);
//creating a database
var dbo = [Link]("mydb3");
[Link]("Database name:", [Link]);
//creating a collection "fac"
[Link]("fac")
.then(() => {
//inserting document
return [Link]("fac").insertOne({ name: "chp", branch: "it", sal: 10000,
domain: ["bda", "ml"], date: Date() }); })
.then(() => {
return [Link]("fac").insertMany([
{ name: "gr", branch: "it", sal: 20000, domain: ["wt", "java"], date: Date() },
{ name: "vr", branch: "cse", sal: 30000, domain: ["ml", "react"], date: Date() }
]) })
.then(() => {
// updating document
return [Link]("fac").updateOne( { name: "chp" }, { $set: { sal: 25000 } } );
})
.then(() => {
// retrieving updated document
return [Link]("fac").find().toArray(); })
.then(result => {
[Link]("Updated document:", result);
})
.then(() => { // deleting documents with domain as ml
return [Link]("fac").deleteMany({ domain: "ml" });
})
.then(() => { // retrieving updated document
return [Link]("fac").find().toArray();
})
.then(result => { [Link]("Updated document:", result);
[Link]();
})
.catch(err => { [Link]("Error performing operation:", err); });
})
.catch(err => { [Link]("Error connecting to database:", err);
});
OUTPUT:
EXERCISE – 10
Aim: Demonstrate Accessing MongoDB from [Link].
[Link]
const { MongoClient } = require('mongodb');
const uri = 'mongodb://[Link]:27017';
[Link]("Before connecting to database");
[Link](uri)
.then(client => {
[Link]("Connected to database!");
[Link]("Database name:", [Link]().databaseName);
//creating a database
var dbo = [Link]("mydb5");
[Link]("Database name:", [Link]);
[Link]("fac")
.then(() => return [Link]("fac").insertOne({name: "chp", branch: "it", sal: 10000,
domain: ["bda", "ml"], date: Date() });
})
.then(() => {
return [Link]("fac").insertMany([
{ name: "gr", branch: "it", sal: 20000, domain: ["wt", "java"], date: Date() },
{ name: "vr", branch: "cse", sal: 30000, domain: ["ml", "react"], date: Date() } ])
})
.then(() => return [Link]("fac").find().toArray();
})
.then(result => { [Link]("Updated document:", result);
[Link]();
})
.catch(err => { [Link]("Error performing operation:", err);
});
})
.catch(err => [Link]("Error connecting to database:", err);
});
OUTPUT:

You might also like