Download as pdf
Download as pdf
You are on page 1of 44
I eeey ae 4-66. Full Stack Web Development Notes ST ee SS es OT TECHNICAL PUBLICATIONS? - on uptnsttorknowtodga x otal UNIT V syllabus MERN STACK - Basic React applications - React Components - React State - Express REST APIs - Modularization and Webpack - Routing with React Router - Server-side rendering Contents 51 5.2 53 54 55 56 57 5.8 59 MERN Stack Basic React Applications React Components Inter Components Communication The props React State Express REST APIs Modularization and Webpack Routing with React Router 5.10 Server-side Rendering 5.11 Two Marks Questions with Answers OT EEE React Full 8 tack Web Development oe et EXD ern stack * MERN stack is a collection of four technologies that are used {© develop full stack web applications. * MERN stack comprises of four technologies namely. © M stands for MongoDB which is used for preparing database © E stands for Express mainly used for developing Node.js web framework, © R stands for React mainly used for developing client side JavaScr ° N stands for Node.js which is an open source, cross-platform, a browser. ipt framework. JavaScript run-time environment that executes JavaScript code outside of * MongoDB, Express.js, and Node js help you build the backend of an application, 12 MERN stack will help you to become a full while React powers the frontend. By learin stack developer. © Components of MERN Stack 1) MongoDB : MongoDB is a NoSQL database where each web [BREE record is a document comprising of key-value pairs that are similar to JSON (JavaScript Object Notation) objects. MongoDB enables users to create databases, schemas and tables. It offers the Mongo shell that provides a JS interface Server for deleting, querying and updating the records. 2) Express : Express is 2 NodeJS framework that simplifies writing the backend code. Express.js has powerful models for URL routing (matching an incoming URL with a server function), and handling HTTP requests and responses. For keeping the code precise, ExpressJS offers a range of =a middleware. Fig. 5.1.1 MERN stack 3) React : React is one of the most popular open-source front-end JavaScript libraries used for building Web applications. It is used to build User Interfaces (UI) for single page web application. It allows developers to create large web applications that can easily change Database |MongoDB the data of the page even without reloading the page. 4) Node.js : It is open source JavaScript Runtime environment, It is Fast - Built on Google Chrome’s JavaScript Engine and has a fast code execution, It allows users to run.code on the server. It comes with the node package manager or npm, enabling users to select from a wide selection of node modules or packages. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge opment 7 .ck Web Development 5-3 aa iu Question | 7. ‘With suitable block diagram explain the concept of MERN stack. wa Basic React Applications Let us start the introduction of ReacUS with a real-world example. Suppose that on a Facebook page, you click the “ike” on some photograph and then by the time you srl down the same page, the ike count gets incremented by some number, even without reloading your Facebook gage. Tis magi change happens because of our ReactS!! ReactlS is an open source, component-based front end JavaScript library maintained by Facebook. This library is responsible only for the view layer of the application. That means this JavaScript js for building user interfaces. Features of ReactJS «Virtual DOM : DOM stands for Document Object Model. It also provides a way to update the content, structure and style of the document. Virtual DOM is a representation of original DOM. When user updates something on the web application, DOM gets updated. Updating the DOM is very slow, most of the JavaScript frameworks update the whole DOM which makes it slower, But actually there is no need to update the whole DOM, instead, these frameworks should update only the part of DOM that is required to update. This is what the virtual DOM does, This is why ReactJS’s DOM manipulation is much faster than other frameworks. Due to this property, whenever any change is made in the web application, then those changes are reflected on the web page within no time. © Components : This feature allows the web developer to create custom elements which can be reused in HTML. © JSX : JSX is an extension of JavaScript syntax. JSX can be seen as 2 combination of javascript and XML. The syntax of JSX is very simple that makes writing components very easy. ‘© One way data binding : The ReactlS is designed in such a way that it follows, unidirectional or one way data binding, That means, data is allowed to flow in one direction at a time, This helps in achieving greater control over the application, This makes helps in increasing the efficiency of an application. ae TECHNICAL PUBLICATIONS® - an up-thrust for knowtedge Full FSteh Web Covent fe Installation of Reacts Open the command romp window and sue the command CAUsere\DELL> npm instal erate eactapp shows The instalation proces wil gt stared. Flowing sesh! {erste ge nt sp ees T [esetcpcapesmrerene rnc a: BRL tio iain if ast hae nab eas (Check ifthe reactS is installed or nt by checking its version Heomestors {:\Users\pELLocreate-reect-app ~-version 5. (c\UserspELL> Thatall iit shows some version number hen the reais inal Creating first program ‘We will create out simple ReacUS application in which we wil simply display a *Weloome User" message Step 1: Go to the directory in which the first application is to be created. At the command pomp issue the command DiseacDemo>creaeeacappfstepp Nth he ftp iste nef he fis pga rte ine Se TERA LATOR? nphatrgy Ee ck Web Development 5-5 om : eo \reactDenorcreate-react-app Firstapp D: | esting 2 new React app in D:\reactOeno\Firstapp. ining packages. This might take a couple of minutes. pstalling packages. This Hesgadling react, react-dom, and react-seripes with c¢a-terrl ] | loadbep:@babel/types: resolveWithn Yodule @babel/helper- step 2: Now locate the index,js file which is present inside the sre folder. Edit it as follows - indexjs import React from ‘react’ import ReactDOM from ‘react-dom’, ReactDOM.render( Welcome, userill, document. getElementByld(‘root') ’ Step 3: Now open the terminal window or command-prompt window and issue the command ‘opm start By this command the web browser gets opened and the output will be displayed. DB React App G_ _— @ localhost:3000 TECHNICAL PUBLICATIONS® - an up-thais for krowedge oe LOC nes 1. What is ReactIS ? Enlist the features of it | 2. Write a simple React application that displays Weleome user TICs sage. _| EX] React Components Components are basic building blocks of actJS application. There are two types of components that are created in ReactIS - y Re Functional Components Class Component 1. Functional components 1s. The functional components return the Functional components are simple JavaScript fun JSX(JavaScript XML)code to render the DOM tree. component ‘llowing code fragment shows the functional function Welcome(props) { return Welcome {props.name}; } Alternatively the functional component can be created using arrow function as follows - const Welcome = (props) => { return Welcome {props.name}; } Note that the function name always start with capital letter. Demo Example Step 1: Open the command prompt and issue the following command D:\reactDemo> create-react-app funcomponent By this command we are creating a workspace by the name funcomponent in which we will be creating our function component. : ip ea TECHNICAL PUBLICATIONS® an up-thust fr knowledge > jy stack Wed Development 5-7 f React stop 2 Locate index.js file in the sre folder of your application and edit it as follows - index dS : ort React from ‘react; port ReactDOM from ‘eact-dom; ‘/index.css'; Peon DisplayStudent(student){ return
“epg>-Student Information.... Note that the function name's first letter must be in capital

jabel> Roll no {student Roll}

: } Passing the values to the functional component const element = //render this component as Id='root’ ReactDOM.render(element,document.getElementByld(root); Step 3 : Open the terminal window or command-prompt. Switch to funcomponent folder and issue the command npm start. The web browser will get opened up automatically and the output will be displayed as follow: D React App = Oo x G_—_O locathost:3000 8 Student Information... Roll_no:111 +/o 0) Name:Chitra F ieee 234567890 ; TECHNICAL PUBLICATIONS® - an up-thrust for knowiedge ——————————— Full Stack Web Development 2, Class component React.Cor To define the class ‘component we have to first create & class and extend class, «elo is class component which Class components are 6 classes that retum to Welcome funetion(as given in Funetional component): Class Welcome extends React. Component { render() { Tetum Welcome, {this props.name}; } } Note thatthe class component must have the render() method fr retuming ISX. Demo Example Step 1 Open the command prompt and issue the following command ‘Di\reactDemo> create-react-app classcomponent By this command we ae erating a workspace by he name clascomponent in which be creating our function component. Step 2: Locate index,s ile inthe sre folder of you application and edit it as follows - index,js impor React from react! impor ReactDOM fom teact-domt impor 'Jindex.css; class Student extends React Component{ render(){ retum
« Student Information. .

} } : const element = Explain the class component in React. 3 ven the ants. 3. Given the difference berween functional and class components EX] Inter Components Communication React is a component-based UI library, When the Ul is split into small, focused components, they can do one job and do it swell. But in order to build up a system into something that can accomplish an interesting task, multiple components are needed. These components often need to work in coordination together and, thus, must be able to communicate with each other. Data must be exchanged among the components In this section we will discuss the communication from parent class to child class. Step 1 Go to the directory in which the first application is to be created. At the command prompt issue the command create-react-app Step 2: Now open the corresponding folder and edit the index.js file as follows index.js import React from ‘react’; import ReactDOM from ‘react-dom' class Student extends React.Component{ constructor(props){ super(props); } render(){ retum

Student Information....

Total Marks: {this props Marks}

} t {this.props.Maths} TECHNICAL PUBLICATIONS® - an up-thnust for knowledgo - stack Web Development 5-11 Resch | pul gjans Marks extends React.Component( ‘onstructor(Props){ super(Props): render(){ retum

Marks of Each Subject are...

|

ke
} + const element 11" Name = "Chitra" Phone = "1234567890" Marks ="95" English="40" Maths="35" Science: 10" >
ReactDOM.render(element,document.getElementById( ‘root ye Step 3: Open the terminal window and issue the command npm start. The web browser will get opened up automatically and the output will be displayed as follows - GS © hecalhost'3000 eee © ‘student Information... Roll.no:t11 Name:Chitra phone:1234567890 Total Marks:95 | Marks of Each Subject are. English:4o jathes | " Science20 | TECHNICAL PUBLICATIONS® - an up-thrust for knowiodgo Full Stack Web Development 5-12 1 React Write a simple React app to demonstrate the communication among the components, El The props The props stand for properties. These are the arguments that are passed to the react components, Props are passed to components via HTML attributes For example consider following HTML script const element = ; The component receives the argument as props object. The code is function Student(props) { return

I have opted for{ props.course}

} The props are basically used to pass data from one component to another, EG React State Basic concept © The React State is a built in object which contains data or information about the component. The component's changing state can be represented by this state object. The change in state can happen as a response to user actions or events. Every time the state of an object changes, React re-renders the component to the browser. * The state object is initialized in the constructor. * The state object can store multiple properties. The setState() function * The setState() is used to change the value of the state object. * State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state. Demo example Step 1: Create a folder with some suitable name. | have created a folder named statedemo by the following command E'S create-react-app statedemo Step 2: Locate the sre folder and edit the index.js file as follows - TECHNICAL PUBLICATIONS® -an upto hnontedgo bp Devolopment 7 | pulse Wel pr 5-13 Reset indexJS ort React from ‘react, import ReactDOM from react-dom' | jgnport ‘/index.css’ | jqass Color extends React. Component { | constructor(props) { super Props); this state = {colomame: Blue"); changeColor() | this setState({colomame: "Golden’}); } render() { return (

My Favorite Color is {this.state.colomame}

button onClick={()=>this.changeColor()}>Click to change color
}- } const element = ReactDOM.render(element,document.getElementByld(‘root')); Step 3: Open command prompt and type the command npm start The output will be | displayed on the web browser DO B Fee app CG © _localhost:3000 My Favorite Color is Blue Click to change color TECHNICAL PUBLICATIONS® - an up-thnust for knowledge Full Stack Web Development 5-14 Click the button and we get © G reac App SG © locathost:3000 My Favorite Color is Golden Click to change color Program explanation : In above application, Ie We have edited index, file. The class named Color is a child class of React Component. In this class, we have written a constructor. This constructor assigns initial this.state with variable colorname as blue. In the render() function of React we have displayed a message using hl tag. Below this message the button component is created. On the button click event the state must get changed, For this purpose, the event handling function changeColor is written. In changeColor() function, the state is changed by using this.setState(). The parameter Passed to this function is state variable colorname with some updated value, Basically, React provides its own method setState(). The setState() method takes a single parameter and expects an object which should contain the set of values to be updated, Once the update is done the method implicitly calls the render() method to repaint the page. Thus when the button is clicked the color value changes from blue to Golden. TECHNICAL PUBLICATIONS® - an up-thust for knowledge - lt stack Web Development 5-15 React pitterence between props and State Prop State Fraps re mumble, That means once we se State holds data and it can be changed over the the props can not be changed. time. i.e. States are mutable. rape can be accessed by child component, | State cannot be accessed by child component Props allow to pass the data from one State holds the information about the components ‘component to another. | Props can be used in both functional as well as | State can only be used in class components. class components, “The parent component sets props for the Event handlers generally update state. children components | Pere 7, Explain the concept of React stare with suitable web application. 2. What is the difference between props and states ? Express REST APIs What is API? ‘API stands for Application Programming Interface. APIs are @ sci of functions and procedures that allow for the creation of applications that access data and features of other applications, services, or operating systems. In other words, if you want to interact with a computer or system to retrieve information OF perform a function, an API helps you communicate what you want to that system so it can understand and fulfil the request. itis basically a software intermediary that allows two applications to talk to each other. For example - When we use facebook, send a message or check the weather on our mobile phone, we use API. For example - If we want to buy a movie ticket, we go to the online ticket booking site, enter movie name, use credit card information, get the ticket, print it. The software that interacts with us to perform all these task is nothing but the API. Following screenshots some well known examples of API. eorege TECHNICAL PUBLICATIONS® - an up-hrust for knowledge Full Stack Web Development Login with one of these available social accounts, ) sirup ise rica | |igteanias G soosle How you'll pay va SB © £ Pay with Other lin ineliy What is REST API? REST stands for Representational State Transfer. It isa set of rules that developers follow while creating their API. Each URL made by the client is a request and data sent back to the client is treated as response. The request consists of, ind Pe Method Headers. 4. Data (1) Endpoint The endpoint (or route) is the URL you request. For example - htp:/ocalhost:8082/ (2) Methods There are various types of methods. But the most commonly used one are as follows - 1) GET 2): PosT 3) DELETE 4) PUT 5) PATCH These methods are basically used for performing CRUD operations. Here C- R- stands for Read, U- stands for Update and D-stands for Delete. stands for Create, TECHNICAL PUBLICATIONS® an up-hastorknowtego up Stack Wob Development ul S oi, Roact Method Purpose GET For getting the data from the server, this request is used. The server looks for the data the client has requested and sends it back tothe client. post This method is used when new resource is to be created on the server. When client uses this method and provides the data, then the server creates a new entry in the database and acknowledges the client whether the creation is successful or not. PUT and These are the two methods that are used when the client wants to update some PATCH resource. When PUT method is used, then that means client wants to update centie resource, And when PATCH method is used, then that means client simply wants to update small part of the resource. “This request is used 0 delete a resource from the server. There are some software tools such as Postman, that help the client to select the appropriate method and issue the URL. Following screenshot is of a software tool Postman, using which we can select appropriate method. http;/fiocalnost:8082/employees Post In URL, femployees acts as a endpoint PUT PATCH A client select any desired method. can DELETE copy HEAD OPTIONS: UNK UNLINK PURGE Lock TECHNICAL PUBLICATIONS® - an up-thnist for knowedge Full Stack Web Development 5-18 React (3) Headers Header are used to provide authentication and other usefil information to client and server. The HTTP headers are property-value pairs separated by Colons(:). For example - “Content-Type: application/json” (4) Data The DATA contains information which the client wants to send to the server. While sending the DATA to the server the methods such as POST, PUT, PATCH or DELETE are used. It is preferred to send the data in JSON format. The format is, Property1:valuel, Property2:value2 Concept of Node JS API The Node, script is popularly used to create REST API. We will write the server script in Node,js. The database is created using MongoDB. The client interface is handled with the help of Postman. REST APL Using Nodes and Express Request Client MongoDB Response| Database Let us understand how to create Node JS REST API with the help of following example Example Code Prerequisite : For creating the Node.js Rest AP] we need following software to be installed in our machine 1) Postman : This is an API client. This client software allows us to enter the request in JSON format and select the commands such as GET, POST, UPDATE, DELETE and so on, TECHNIGAL PUBLICATIONS® - an up-thnst for knowodge ry stock Web Development 5-19 React 2) MongoDB : This is a database package. We need MongoDB compass to be installed along with the mongoDB server application. The MongoDB compass is a graphical tool for handling database operations. 3) NodeJS : This is of course used for creating an API in js file. step 1: Make a new folder in your current working directory for creating Rest API. Here I | am creating a folder named RestApiDemo step 2 : Now open the command prompt window and create package,json file using npm init command, Following screenshot illustrates the same. ‘Atthe command prompt simply type the command inpm init ‘Then hit the enter button, You can add the values of your choice or simply go on pressing enter key and accept the default value. tren - a x \yiodestnanple\testasoenoicom int Pease eeerituat you teh cresting» package sen le Le etree a the ent common ites, and Erles to guess sensibe defelts. se “nm help int’ for definitive deconantat on on these Fields rd emctly sat they ee “nom intel eps” afterards to installa package and ve Heat's dependency In the sachage. 530m fT, tage rane eeseeisene) nteynoirt: (Sraee)3) oP)» cat coe Bice G0 Stine to 0: odersesomles\tetioidenloachner.j86 ¢ Seno \terars no test specifiy” BF eit Step 3 : Now install some more packages that are required for creating this Rest API Installation of express module Issue the following command prompt:\>npm install express TECHNICAL PUBLICATIONS® - an upthrust for knowledge Full Stack Wet) Development Pete Stemetes test Asitemenge Hostel eames t el Tem tt heap toe mnressananye Installation of mongodb module Issue the following command prompt'\npm install mongodb te )Sivoar es \RestAoiDrawingm tell songs (dl 8.0 he repository {Held s 1 contribetort and audited 66 packages in 1.2158 ler Installation of mongoose module Issue the following command prompt:\>npm install mongoose Bmw Jo uate txamoles \RestActomssipe install mongoose restophdeml 0,0 We repository (eld . wengucsee 12.0 aaded 15 packages from #5 contrtbutors and audited 81 packages in 1.bAls 2 packages are looking for funding fin "eee find for details tome & wulseratiidities eC name es \RestHpibemsy Installation of nodemon Issue the following command at the command prompt prompt:>npm install -g nodemon -save-dev TEGMUCAL PUBLICATIONS? nop at inomeage wa pul stack Wt Development SF ste dev pecs registry url. 1.0 checking instal able punt stxomes\testheiOewnrere stall ‘= 1A feterretadata ‘The sample package,json file will show you all these dependencies of the modules you have | installed just now package json Tj package - Notepad | | tie eat Fomat View Helo { ; | “restapidemo”, 0.0", this is my Rest API Demo Project”, uthor": "A.A.Puntambekar” , icense": “ISC", | “dependencies”: { | express”: "4.17.1", | *mongodb": "43.6.4", “mongoose”: "A5.12.0" } } Note that | have added following line in package,json file so that as soon as I save any changes inthe file, the output gets reflected immediately. I need not have to run the app.js file every time, “start” :“nodemon app.js” Step 4 : Now create your main server in a file named app.js. TECHNICAL PUBLIGATIONS® - an up-Pwrust for knawiecye Full Stack Web Development app.js const express = require(express}), const mongoose = require( mongoose’); database URL for the url = ‘mongodh://localhost/EmployeeDB} Connecting to MongoDB database const app ~ express) using Mongoose package mongoose connect(utl, {useNewUnParsertrue}) const con = mongoose connection //getting the connection object con. onfopen’) => { //on opening the connection, connecting with database console log(Connected to Database’) » app.ure(express json()) const employeeRouter = require(./routes/employees’) //initial endpoint app.use(/employees.employeeRouter) app listen(B082, () = >{ console log("Server Started!!!") 3p) Step 5: Create a folder named routes. Inside the routes folder create a file named employees.js. This file will handle the GET and POST requests of REST API. Using rting the data into the database. The GET POST request we can create the API by in request will retrieve and display the data from the database. Thus routing of GET and POST requests is done in this file. employees.js const express = require(express’); const router = express Router(): const Employee = require(’./models/employee'); This is a router program that routes on receiving the particular type of request router get’, async(req.res) = >{ uy const employees = res json(employees) Handing GET command issued by the client, and using find(), displaying data present in the Employee database wait Employee.find() } catch(ert) { res.send(Error is: '+err) » TECHNICAL PUBLICATIONS® - an up-thrust for knowtedge - Web Developn stock Handling the POST request. The data is received here from client. Hence we use req.hody followed by name of the data field outer. post asyno(rea.tes) => { const employee = now Employro({ name: req.body.name, : designation: req. body.designation y ey const e1 = await employee.save(); resjson(e1); } catch(er){ res.send('Error is: '+er) » module.exports = router e another folder named models. Inside modi employee.js. This file will describe the Schema. The fields of the document are described in this file along with data type this file. Note that the schema is specified in JSON format. Step 6 : Now creat els folder create a file named and some other description is mentioned in employee.js const mongoose = require(‘mongoose’) const employeeSchema = new mongoose.Schema({ name: { type: String, required: trie Preparing the schema } for the database designation: { type: String, required: true } v module.exports = mongoose.model(‘EmployeeemployeeSchema) Step 7 : For better understanding, the folder structure of this project can be viewed in the following explorer window TECHRUCAL PUBLIGATIONS® «an upstrat or rowsodoe na Full Stack Web Development §- 24 React ¥ RestApiDemo models ‘employee js D> node_modules V routes ‘employee js appjs package-lock json package json Step 8 : For getting the output, Open the command prompt window and issue the following command. D:\NodeJSExamples\RestApiDemo>nodemon run start You should get the “Server started” and “Connected to Database” messages 1B Commane Prompt -nogeran run stat b: \tode3SExamples\Restip{Denornodenon run start (rode-13884) warning: Accessing non-existent property “HongeError* of wodul Je exports insige circular dependency (Use rode "-trace-marnings ...° to show where the warning was created) (node:13842) Deprecationiarning: current Server Discovery end Monitoring en Jgine is depreceted, end will be renaved in a future version. To use the new ‘Server Discover and Monitoring engine, pass option { useUnifiedTopology: t Jrve } to the MangoClient constructor. Iserver Started!!! Jconnected to Database Now, Open the Postman and click on Create Request. Select the POST command issue the URL as http:/Aocalhost:8082/employees And then click on Send button TECHNICAL PUBLIORTIONS® en up tha oriamago d —£“a stack Web, Development 5-25 React Tan ie | | | | g penne treet 22 tent Once we hit the send button we get the result by generating the unique _1 id for the data which wehave inserted. It can be viewed as follows, In this, manner we can insert more data by selecting the Post command, This data is sent to the | app,js server and then getting stored in the MongoDB database. In order to retrieve data being stored, we can use GET method on Postman client and see the complete data in the form of JSON structure. We can verify the data by opening the database created in MongoDB ‘TECHNICAL PUBLICATIONS® - an up-tinst for knowtedge Full Stack Web Development 5-26 React "| <—— . 6 5: EnployeeDB employees ween EET men SS GEST = In this manner we have created our REST API for employee details. DA tes | 7 Wi e and explain a simple application using REST HTTP method APIs in Reacts. EX] Modularization and Webpack Modularization is a technique which helps in code organization by splitting the code into smaller parts. The modular architecture involves breaking down a program into sub- programs called modules. Each module is associated with certain functionality. The module helps to understand the entire code. React is one of the most popular front-end technology that uses the component structure for modularizing. React uses something called component structure, where each component has its own file. To access the code in the files, we use import and export. Webpack in react is a JavaScript module bundler that is commonly used with React to bundle and manage dependencies. The webpack takes all the necessary JavaScript files, CSS files combine them into a single bundle that can be loaded by the browser. For using the webpack in React we use webpack.config,js fille. Following are the sections of webpack.config,js file — o Entry : The entry refers to the entry point of React application. All the React components branch out from app.js and app,js is found inside index.js. The entry attribute is defined as follows - TECHNICAL PUBLICATIONS® - an up-thrust for nowtedgo cf Web Development 5-27 rl React, | odule.exports = { ntry!./app/indox.s | 9 Output : After completing all the processes, the React webpack creates bundle file. Using output we can specify the name and location of final output file, For example - mmodule.exports = entry:./app/indexs\ output: { | path: path oin(_dimame, "/dist),// the bundle output path filename: "bundle.js", // the name of the bundle Loader : Loader is like compiler, it checks for different types of files and match them with their appropriate loaders for handling them. For example - module.exports = module: { loaders:l { test: \s|isx)8/, exclude: /(node_modules)/, Joader: 'babel-loader’, ‘There are certain rules used in the module and those are — test Ttchecks for particular file type(such as js.ss.jsx and so on) use Ti specifies a list of loaders used by any specific file type. exclude Tihelps the developer to decide which files should not be processed. Include Tehelps the developer to decide which files should be processed For example - { test:/\.css/, usei{'style-loader'/css-loader] } © Plugins : An effective plugin interface is included with Webpack. The majority of ebpack’s functionality makes use of this plugin interface. As a result, Webpack is more flexible. © Mode : The mode in React helps developers to use different set ups when they are in development and production mode. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge Full Stowck Wi React Development 5 © devServer : 11 is used to quickly build the applica moduleexports | devierver { contentBase: '/dist port 3000 ) Use of Babel Babel 1s « JavaScript compiler that converts modem JavaScript code into the version which is compatible with all the browsers. Babel transpiles modern JavaScript for use in React Components. The transpiler is a tool used to convert source code into another source code of same level The main reason we need babel in modularization is that it gives us the privilege to make use of the latest things JavaScript has to offer without worrying about whether it will work in the browser or not. Demo Example Step 1: Create a folder with some suitable name, | have created a folder named webpack_example, Create an index.him! file inside it Now initialize npm using mpm init -y command jell Ube aie, Step 2: Install react and babel packages Install react Installing babel Step 3: Create webpack.configjs inside your folder(In my case it is webpack_example). Edit the code as follows TECHNWCAL PUBLICATIONSS an upon or inondedpe stack Web Doveloprant Frag _ f yobpack.config,js const path = reqtuire(‘path’) module.exports = { entry: /app/index.j9 output: ( path: path join(_dimame, ‘/dist’), // the bundka output pal filename: "bundle js’, // the name of the bundle module:{ rulesi| { test:/\js9/. exclude:/(node_ od use:{ Ioader babel-loader options:{ presets:("€ bol/preset-env’, ‘@babel/proset-react’} test:/\.cs5/. use:|'style- s-loador'| loader’ cs Create two folders name! app and dist. Inside the app folder create an index.js file The entry point must be index,js. The output will be in bundle.js which will be created by the webpack in the dist folder v app eyelets cana tyh TECHNICAL PUBLICATIONS® ~ eo up-meust for knciwedtge Full Stack Web Development - 5-30 UU DEBUG CONSOLE Bia YING Ps E:\webpack_example> npm install jquery --s added 1 package, and audited 2 packages in 9e6ms found @ -vulnePibilities PS E:\webpack_example> fj Step 6: The source files in app folder are as follows - index.js import name from '/anotherModule.js'; import '/mystyle.css' import $ from jquery’ import React from react’ import ReactDOM from ‘eact-dom' class App extends React. Component{ render() { retum (

Welcome {name} ) } 3 ReactDOM.ender{ document.getElementByld(‘roct’)) anotherModule.js const name = ‘Parth’ export default name; mystyle.css body { background: khaki; i hi{ color-red; + Reac TECHNICAL PUBLIGATIONS®. an up or krowlodge _— Web Development: 5-31 React ul St00k index.htm! ZipOCTYPE htrnl> entml> ‘ctitle>Modularization and WebPack Demo
script sto="dist/bundle js"> step 7: Run and build the application using the command mpm run start Ps E:\webpack_example> npm run start > webpack_example@1.0.0 start > webpack -w --mode development Step 8: Open the index.html file in suitable web browser DD Medusnsaton ond wepeck x EG _O hile | Efebpack.example/inderhiml Welcome Parth Program explanation ; In above code, 1) We have created two ,js files namely indexjs and anotherModule,js and one .ess file named mystyle.css. These are bundled together using webpack module and displayed the output on the browser. TECHNICAL PUBLICATIONS® - an up-thrust for knowledge Full Sta Wot Development 5:32 — React ) In index.js file we simply render the “Welcome” message with the name whieh jg obtained from anotherModule,js file. For displaying the welcome message, the style is applied to WY and body tags and these styles are defined in myStyle.css file. The index js, Ayle.css files are packed together ing Webpack and result is anotherModule,js and my displayed on the browser. Review Question i Write a web application of your choice to demonstrate the webpack and modular ization concept. EX] Routing with React Router Routing is a technique by which the user is directed to different pages based on their action, Reactl$ router is a single page application. The single page application is a web application that interacts with the user by dynamically rewriting the current page, rather than loading entire new: pages from the server. When a user types a specific URL into the browser and if this URL path matches any ‘route’ inside the router file, the user will be redirected to that particular route Most of the popular sites such as Youtube, facebook and Instagram make use of Reacts for rendering multiple views via routing technique Ther 1. react-router : It provides core routing components and functions for the React Router application React-router-dom : This package enables the user to implement dynamic routing in a web app. are two important packages that are used while using Reacts routing. React Router is the core package for the router. React Router DOM contains DOM bindings and gives you ace s to React Router by default ‘The React Router API is based on following elements : © : The router that keeps the UI in syne with the URL. © : Renders a navigation link. © : Renders a Ul component depending on the URL. © : It is used for handling the dynamic URL, TECHNICAL PUBLICATIONS® - an up-thrust for, ‘nowledge _ React index js =| welcome js routes to ¢ Welcome page @- | e Contact page @--[ (ues! 6 contacts Fig. 5.9.1 top 1: Create folder for developing routing application using following command DireactDemo> ereate-react-app routerclemo step 2: Install the package for router using the command ‘piveactDemo\routerdemo>npm install react-router-dom Step 3: Inside the sre folder create a js file. I named it as welcome. js(note that here the w is in small letter) welcomejs import React from ‘react’; function Welcome(){ retum(

Welcome User!!I!

‘ yt export default Welcome Step 4 : Again create one more js file inside the sre folder. 1 have named it as contact.js(Again note that c is in small letter here.) contact.js import React from ‘rea function Contact(){ Teturn( ‘
Full Stack Web Development 5-34 React Step Locate index,js from sre folder. Specify the routes for the above created two files welcome,js and contaet,js files. index,js import React from ‘react’; import ReactDOM from 'react-dom'; import {BrowserRouter, Link, Switch Route,Routes} from ‘react-router-dor import Welcome from ‘welcome’: import Contact from '/contact’; function App(){ ‘

Router Demo
  • Contact Page

) } ReactDOM.render( , document.getElementByid{(root" v ‘} /> } /> Step 6 : Open the terminal window and issue the command npm start 2G Router Demo + Welcome Page + Contact Page TECHNICAL PUBLICATIONS® - an up-thrua for knowtedge we a Stack Web Development 5-35 React ifwe click on Welcome Page link then rr: —Ct—=Sste = | « G_ © bocalhost:3000; eo & @ S| Router Demo | + + Welcome Page Ifwe click on Contact Page then CO Ioeahose 3000/e0nta0. 43 3 o | lo Router Demo + + Welcome Page + Contact Page Phone: 1234567890 Email:abe.xyz@gmail.com Aceon | 1. Explain with suitable application for demonstrating routing with React JS. FEgrnnCA PUBLICATIONS an upto krowedge Full Stack Web Development 5296. React Server-side Rendering © Server Side Rendering(SSR) is a technique in which the HTML contents of React application are displayed on the server side before sending it to client. © With SSR the initial page load is faster and it improves: the search engine optimization, © In server side rendering technique the HTML page is created at the server side with al] the necessary contents of the site and then it is sent back to the user. The user will get fully render HTML page that contains all the necessary information without having to wait for and JavaScript or CSS file to load. That means the user who v will be able to see everything much faster than if they were looking at the blank screen while waiting for JavaScript files to load. s the web site © Server-side rendering is used in many popular JavaScript frameworks, including Angular and React. There are also other frameworks like Preact, which aims to be a lightweight alternative to React. © In general, websites that use server-side rendering include social media sites such as Facebook and Twitter, as well as e-commerce websites like Walmart and Amazon. © For example - Suppose we have a React application that displays the list of some articles. When user requests the page, the server retrieves the information from backend API and uses React’s rendering engine to generate HTML content on the server-side. After creating the HTML file, it is sent to the client along with necessary JavaScript files User can immediately display this HTML page on the web browser. After the initial page ad, the application behaves like a typical React application and any additional user interaction is handled by the client-side JavaScript code. This means that the user experience is still interactive and dynamic. ¢ The process of utilizing the HTML rendered on the server for a component is called hydration. The ReactDOM.render() function does not perform hydration but replaces the entire HTML tree by rendering the component from the scratch. For hydration, we need to use ReactDOM.hydrate() function. // import App components import { App } from '/components/app’ // compile App component in ‘#app" HTML element ReactDOM.hydrate( , document.getElementByld( ‘app’ )); © This function works exactly the same as the render function but it utilizes the server-side rendered HTML instead of rendering the component. However, it expects the server- side rendered HTML and HTML rendered by the App component to be exactly the same. If there is a mismatch, it can lead to unexpected results, TECHNICAL PUBLICATIONS® - an up-thust for knowdedge La fie a up stack Web Development 5-37 React ayantages of server-side rendering a ; oly 1) Easy Indexing by search Engines : As contents are rendered at the server side before sending it to the user, the search engines can easily index and erawl it. 2) Fast load time : The server side rendering improves the speed of page loading . This improves the overall user experience. Clientside rendering is not supported by sebook’s Open Graph Protocol or Twitter Cards, for example. If social media sharing is 4) Indexing with the use of Social media F ‘an important part of marketing strategy, server-side rendering may be a better option. pisadvantages of server-side rendering 1) Increased burden on Server : Due to server side rendering, it becomes costly and | resource intensive, the server has to bear the full burden of rendering contents for users. 2) Slower page rendering : The Server side rendering is ideal for static HTML site generation, but for complex applications it may result in slower page rendering. pifference between Server-Side Rendering(SSR) and Client-Side Rendering(CSR) : ‘+ In server side rendering, the HTML contents are generated on the server on the other hand in client side rendering, the HTML contents are generated on the client side along with Javascript © The SSR sends the pre-rendered HTML page to the client. While CSR sends the minimal HTML page to the client. * SSR requires additional server-side configuration while CSR requires less server-side configuration. * SSR is useful for improving the initial page load time and search engine optimization. On the other hand CSR is suitable for applications with dynamic user interfaces that require frequent updates without refreshing the page. Gis AUR) 1. What is server side rendering ? Explain. 2. Give the advantages and disadvantages of server side rendering. 3. What is the difference between server side rendering and client side rendering. Full Stack Web Development 5-38 React Two Marks Questions with Answers. Q.1 What is MERN stack ? Ans.: MERN stack is a collection of four technologies that are used to develop full stack web applications. MERN stack comprises of four technologies namely, © Mstands for MongoDB which is used for preparing database. © E stands for Express mainly used for developing Node,js web framework. © R stands for React mainly used for developing client side JavaScript framework, © N stands for Node.js which is an open source, cross - platform, JavaScript run - time| environment that executes JavaScript code outside of a browser. Q.2 What is ReactJS ? Ans. ; ReactlS is an open source, component - based front end JavaScript library maintained by Facebook. This library is responsible only for the view layer of the application, That means this JavaScript is for building user interfaces. Q.3 What are functional components in ReactJS ? Ans. : Functional components are simple JavaScript functions. The functional components retum the JSX(JavaScript XML)code to render the DOM tree. Following code fragment shows the functional component function Welcome(props) { yetum Welcome {props.name}

; } Altematively the functional component can be created using arrow function as follows - const Welcome = (props) => { retum

Welcome {props.name}: } Q.4 How to define class components in ReactJs ? Ans.: To define the class component we have to first create a class and extend React. Component class. Class components are ESG classes that return JSX. Below, is a class component which is similar to Welcome function(as given in Functional component) : class Welcome extends React.Component { render() { retum

Welcome, {this.props.name}

; TECHNICAL PUBLICATIONS® - an up-thrus fr knowledge | — yp Stack Web Development 5-39 _ hat is the use of setState() function in ReactJS 7 as Wt ans. The getState() is used to change the value of the state object. State can be updated in response 10 © This is done using the setState() method. The setState) method enqueues all of the updates vent handlers, server responses, or prop changes. made to the component state and instructs React to re-render the component and its children with the u a6 What is modularization ? ipdated state. Ans. = Modularization is a technique which helps in code organization by splitting the code into smaller parts. ‘The modular architecture involves breaking down a program into subprograms called modules. Q.7 What is Webpack ? sans. Webpack in react is a JavaSeript medule bunder that i commonly used with React to bundle and manage dependencies. The webpack takes all the necessary JavaScript files, CSS files combine them into a single bundle that can be loaded by the browser. Q.8 What is Babel ? ‘ans, : Babel is a JavaScript compiler that converts modem JavaScript code into the version ‘sich is compatible with all the browsers. Babel transpiles modem JavaScript for use in React Components. The transpiler is a tool used 0 convert source code into another source code of same level. “The main reason we need babel in modutarization is that it gives us the privilege to make use ofthe latest things JavaScript has to offer without worrying about whether it will work in the browser or not. Q.9 What is React Router ans. + Reactl$ router is a single page application. The single page application is a web application that interacts with the user by dynamically rewriting the current page, rather than loading entire new pages from the server. When a user types 2 specific URL into the browser and if this URL path matches any ‘route inside the router file, the user will be redirected to that particular route. Q.20 List and explain the packages that are used In ReactJS routing Ans. : 1. react-router : It provides core routing components and functions for the React Router application. 2. React-router-dom : This package enables the user to implement dynamic routing in a web app. “EDInIEAL PUBLICATIONS - 7 ott ornoteaae Full Stack Web Development 5-40 React Q.11 What is Server side Rendering (SSR) ? Ans. : Server Side Rendering (SSR) is a technique in which the HTML contents of React application are displayed on the server side before sending it to client. With SSR the initial page load is faster and it improves the search engine optimization. In server side rendering technique the HTML page is created at the server side with all the necessary contents of the site and then it is sent back to the user. The user will get fully rendered HTML page that contains all the necessary information without having to wait for JavaScript or CSS file to load, Qog TECHNICAL PUBLICATIONS® - an up-thrust for knowledge yr Time: Three Hours] Qt Q2 a3 a4 as a6 Q7 as ag SOLVED MODEL QUESTION PAPER [As Per New Syllabus] Full Stack Web Development Semester - V (IT) [Maximum Marks : 100 Answer ALL Questions PART A - (10x 2 = 20 Marks) what is web development framework ? (Refer Two Marks Q.1 of Chapter - 1) What is full stack ? (Refer Two Marks Q.10 of Chapter - 1) What is Node.js ? Give its uses. (Refer Two Marks Q.1 of Chapter - 2) Explain the use of CliemRequest object. (Refer Two Marks Q.12 of Chapter - 2) What is NoSQL ? (Refer Two Marks Q.1 of Chapter - 3) Explain the createUser command in MongoDB. (Refer Two Marks Q.5 of Chapter - 3) What is express. Enlist the features. (Refer Two Marks Q.1 of Chapter - 4) What is the use of ngModule in angular ? (Refer Two Marks Q.10 of Chapter ~ 4) What are functional components in ReactJS ? (Refer Two Marks Q.3 of Chapter - 5) Q.10 What is react router ? (Refer Two Marks Q.9 of Chapter - 5) PART B - (5 x 13 = 65 Marks) tt a) i) Explain the full stack web development framework in detail with suitable block diagram. (Refer section 1.7) 113] ° oR b) i) Explain MVC architecture. Also enlist the features of MVC architecture. (Refer section 1.6) (61 ji) What are the components of basic web development framework ? Explain each (Refer section 1.1) 17] Q.12 a) i) IWhat is Node Package Manager(NPM). Also explain the command line options ofnpm. (Refer section 2.4) fal ii) What is stream ? Explain how to perform read and write operations in Node,js using stream. (Refer section 2.10.2) (61 (M-1) Full Stack Web Development Maz Solved Mode! Question Paper OR b) i) How event listener is handled in Node,js. Explain it with suitable example code, (Refer section 2.7) 7] ti) Explain any nwo built-in modules in Node.js. (Refer section 2.4.3) 16) Q.13 a) i) Elaborate the steps used for connecting the MongoDB with Node.js (Refer section 3.8) 15) ii) Explain with suitable examples, CRUD operations in MongoDB. (Refer section 3.7) 18} OR b) i) How to create an index and find the index in MongoDB ? Explain it with suitable example, (Refer section 3.11.1) 15] it) Explain the i) MongoDBClient object and ii)db object with methods associated with it, (Refer section 3.9) 18] Q.14 a) i) Explain the implementation of routing technique in express with example. (Refer section 4.2) 18] ii) Write a simple application in TypeScript demonstrating the interface. (Refer section 4.7) {5} OR b) i) Explain with suitable block diagram, the angular architecture. (Refer section 4.14) 15) il) Write a code in TypeScript to implement the simple arithmetic calculator application. Make use of interface. (Refer example 4.7.1) [8] Q.45 a) i) Explain the class components in ReactJS. (Refer section 5.3) v7 ii) What is react state ? Explain it with example code. What is the difference berween props and state. (Refer section 5.6) 161 OR b) 4) Explain the concept of modularization and web pack in React,js. (Refer section 5.8) 13] PART C - (1x 15 = 15 Marks) . Q.16 a) Write an application in Node.js demonstrating the ClientRequest and ServerResponse object with necessary illustrations. (Refer section 2.11) [15] OR b) Create a simple student database in MongoDB and display all the records in sorted manner. (Refer section 3.10) 15] a00 TECHNICAL PUBLICATIONS® -. ‘9n up-thrust for knowledge wih Mai

You might also like