0% found this document useful (0 votes)
4 views86 pages

WDF Unit 5 Digital Notes

This document is a confidential educational resource for RMK Group of Educational Institutions, detailing the course 'Web Development Frameworks' for the 2023-2027 batch. It includes course objectives, prerequisites, a comprehensive syllabus covering advanced JavaScript and ReactJS, as well as course outcomes and mapping to program outcomes. The document also lists faculty members, equipment requirements, and resources for students to enhance their learning experience.

Uploaded by

oopsitsmysteria
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)
4 views86 pages

WDF Unit 5 Digital Notes

This document is a confidential educational resource for RMK Group of Educational Institutions, detailing the course 'Web Development Frameworks' for the 2023-2027 batch. It includes course objectives, prerequisites, a comprehensive syllabus covering advanced JavaScript and ReactJS, as well as course outcomes and mapping to program outcomes. The document also lists faculty members, equipment requirements, and resources for students to enhance their learning experience.

Uploaded by

oopsitsmysteria
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
You are on page 1/ 86

1

2
Please read this disclaimer before proceeding:
This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document
through email in error, please notify the system manager. This document
contains proprietary information and is intended only to the respective group /
learning community as intended. If you are not the addressee you should not
disseminate, distribute or copy through e-mail. Please notify the sender
immediately by e-mail if you have received this document by mistake and delete
this document from your system. If you are not the intended recipient you are
notified that disclosing, copying, distributing or taking any action in reliance on
the contents of this information is strictly prohibited.
22IT407
WEB DEVELOPMENT FRAMEWORKS
(Lab Integrated)
Batch / Year / Semester: 2023-2027 / II / 4

Name of the Faculty Members


RMKEC
1.Dr. S.D. Lalitha, ASP, CSE, RMKEC
2.Ms. V. Haritha, AP, CSE, RMKEC
3.Ms. J. Latha, AP, CSE,RMKEC
4.Dr. G. Manikandan, Professor, ADS, RMKEC
5.Dr. Gladiss Merlin N R, ASP, ADS, RMKEC
6.Dr. A. Ponmalar, ASP, ADS,RMKEC
7.Dr. P. Umaeswari, ASP, CSBS, RMKEC
8.Dr. M.S. Girija ,ASP,CSD,RMKEC
9.Ms. M. Kanniga Parameshwari, AP ,IT, RMKEC
RMDEC
1.Dr. G. Amudha , Professor & Head, CSBS, RMDEC
2.Dr. P.M. Joe Prathap , Professor, CSE, RMDEC
3.Mrs. D. Vishnu Sakthi , AP, CSE, RMDEC
4.Dr. K. Roslin Dayana, ASP, CSE, RMDEC
5.Dr. R .Jothilakshmi , ASP, IT, RMDEC
6.Dr. B. Kalpana, ASP, IT, RMDEC
7.Dr. K. Sudharson, ASP, AIML, RMDEC
8.Dr. K. Sudha, ASP, CSBS, RMDEC
RMKCET
1.Dr. Sivasubramanian R , ASP, CSE, RMKCET
2.Dr. Prasath R, ASP, CSE, RMKCET
3.Ms. Saranya R, ASP, CSE, RMKCET
4.Dr. L. Maria Michael Visuwasam, ASP, ADS, RMKCET

4
1. CONTENTS
S.NO. CONTENTS PAGE NO

1 Contents 5
2 Course Objectives 6
3 Pre Requisites 7
4 Syllabus 8
5 Course Outcomes 13
6 CO- PO/PSO Mapping 14
7 Lecture Plan 15
8 Activity Based Learning 16
9 Lecture Notes 17-54
10 Assignment – 1 to 5 55-57
11 Part A Questions & Answers 58-77
12 Part B Questions 78
Supportive Online Certification
13 79
Courses
14 Real time Applications 80
15 Contents Beyond the Syllabus 81
16 Assessment Schedule 82
Prescribed Text Books & Reference 83
17
Books
18 Mini Project – 1 to 5 84-85

5
2. COURSE OBJECTIVES
OBJECTIVES:

The Course will enable learners:

● To understand web semantics and related tools and framework

● Able to get hands on latest JS based web frameworks

● To develop a scalable and responsive web application

● To develop an industry ready application web enterprise feature

6
3. PRE REQUISITES

• Pre-requisite Chart

22IT407
WEB DEVELOPMENT
FRAMEWORKS

22CS102
SOFTWARE DEVELOPMENT PRACTICES

7
4. Syllabus
22IT407 – WEB DEVELOPMENT FRAMEWORKS (Lab Integrated) – L T P C - 3 0 2 4

UNIT I - ADVANCED JAVASCRIPT – 9+6


Introduction to HTML5 and CSS3, Media Queries, JS, DOM, BootStrap, Variables, Loops,
Operators, Scope, Hoisting, Arrays, Spread, REST, DeStructuring
List of Exercise/Experiments
1)Create a JS Object for Bank Account (with attributes like customer name, account type,
balance, date of creation, bank name, branch name, pan card number). Using JS Object
keyword, try to perform following activities
➢ List down all the entries of the bank object
➢ Check the existence of a key
➢ If key found, get the value for the key
2)Spread Operator
➢ Merge Customer and Account Arrays
➢ Update the Customer Object with the new values
➢ Develop a function that takes a Spread Argument and calculates total balance.
UNIT II - INTRODUCTION TO REACTJS - 9+6
Class-Inheritance, Methods, Extended Class-Map, filter and Reduce Functions, Functions -
Arrow Functions, Lambda Expressions, REST - Introduction, Why JSX, Hello World Apps,
Project Structure
List of Exercise/Experiments
1) Create a list of Bank Objects (same kind of object you used in above lab,
but in an array format)
➢ Display the banks where balance is greater than 200
➢ deduct 10% of the Bank account balance, as part of monthly service
fees
➢ Display the banks where balance is greater than 200 and branch
code is “Chennai”
➢ Add a new Bank to the given array
➢ Delete a bank from the array (use splice operator)
➢ Calculate the total balance of all bank accounts

6
4. Syllabus
1) Develop a Scientific calculator that does following operations
➢ Rounded Value
➢ Area of Circle
➢ Calculating of Sin, Cos and Tan functions
➢ Permiter of a Rectangle
➢ Employ Arrow functions
➢ Employ HOC
UNIT III - REACT COMPONENTS – 9+6
Class vs Functional Components, Lifecycle methods - React Class Based Components
– component DidMount, WillUpdate, shouldupate, didcatchetc - State - UseState,
UseRef, USeEffect,UseHistory Usage and Props(difference, when to use what, mutable
or immutabilty,direction of flow), PropTypes, Auxillary Components, Controlled and
Uncontrolled Components,Component Interaction (Parent to Child and Child to
Parent), Iteration & Conditional Response
List of Exercise/Experiments
1) Create a collection of Customer by using
➢ Weak Map and Map Collection in JS
➢ Show Case the different feature set of the same.
2) Add Login Page, Dash Board Page, Admin Page
➢ Enable React Routing
➢ Add React Protected Route, for authorization
UNIT IV - REACT LIBRARY – I – 9+6
Event Bubbleup - Component Wrapper - Integration of CSS Modules - Forms
Validations(YUP, Formik, Standard), Events Handling, Data Binding - Redux
List of Exercise/Experiments
1) Develop a React application that has User Registration Form w field
level validations, data submission to a rest api end point, boot strap
for responsive.
➢ Use YUP or Formik to implement the same
4. Syllabus
2) Build a Redux Counter Application
Requirements:
➢ React application with Redux integrated.
➢ A counter with:
➢ Increment button
➢ Decrement button
➢ Reset button
➢ Display the current counter value.
UNIT V - REACT LIBRARY – II – 9+6
Custom Hooks, HTTP - Fetch, Axios, and Context API, Services, Behaviour Subjects -
StateLess, StateFulll and Container Components, Error Handling - Build, Env, CORS, Unit
Testing w React Testing Library - Introduction to react-native - Introduction to
StoryBook
List of Exercise/Experiments
1) Employ backend API for Login Page functionality (authentication). Post login, store
the user context (received from the back end server) in browser’s session storage as
objects. And use the same as creds during protected route verification.
➢ On the dashboard page, have a grid of Students. The data has to be bought from
backend api
➢ Employ useref, useeffect & usestate, and useHistory
2) Enable Exception Handling
3) Enable HOC and Aux Components
4) Implement React-Testing Library
5) Basic Context Setup
Objective: Set up a React Context to manage theme (light or dark).
➢ Create a ThemeContext using React.createContext.
➢ Create a provider component ThemeProvider with state to toggle between
"light" and "dark" themes.
➢ Use the context in a functional component to display the current theme.
➢ Add a button to toggle the theme.
4. SYLLABUS
Business Use Case Implementations

1) Student Management System

2) Retail Bank System

3) E-Commerce System
4) Student LMS Management System
TOTAL:45+30=75 PERIODS

TEXTBOOK:

1. David Flanagan, Javascript The Definitive Guide, Paperback, 7th Edition, 2020.

2. David Choi ,Full-Stack React, TypeScript, and Node: Build cloud-ready web
applications using React 17 with Hooks and GraphQL, Paperback – Import, 18
December 2020
3. Mehul Mohan, Advanced Web Development with React, Paperback – 1 January
2020

E-RESOURCES:
1.Parental Website - https://reactjs.org/
2.The Road to Learn React: Your journey to master plain yet pragmatic React.js by
Robin Wieruch.
3.Learning React: Functional Web Development with React and Redux by Alex Banks
and Eve Porcello
4. Learning React by KirupaChinnathambi
5. "React Up & Running" by StoyanStefanov
6. https://www.edureka.co/reactjs-redux-certification-training
7. CodePen
8. CodeSandbox (Preferred)
9. Stackblitz

11
4. SYLLABUS
LIST OF EQUIPMENTS:

• NodeJS (v9.11.2)

• Github as code repository

• Visual studio code as IDE

• RTL as unit testing framework

• Responsive design w bootstrap

• ReactJS installation (v17)

• Chrome / FIreFox Browsers (latest)

• Responsive using Media Queries & Bootstrap Material & Antdesign

• Design based Apps

12
5. Course Outcomes
Course Outcomes with Knowledge Levels:
CO1: Personalize web pages using text formatting, graphics, audio,
and video. - K3
CO2: Hands on knowledge on Rest API , propTypes. - K3
CO3: Able to develop a web application using latest React
Framework – K3
CO4: Apply various React features including functions,
components, and services. – K3
CO5: Able to develop application using ReactJshooks. – K3
CO6: Design and integrate complex web components to enhance
user interface and user experience in React applications. – K5

11
6. CO-PO/PSO Mapping

PROGRAM OUTCOMES PSO


CO
PO PO PO PO PO PO PO PO PO PO PO PO P P P
S S S
1 2 3 4 5 6 7 8 9 10 11 12 O O O
1 2 3
CO1 3 3 3 1 1 - - - 2 1 - 1 - - -

CO2 3 2 3 1 2 - - - 2 1 - 1 - - -

CO3 3 3 3 1 2 - - 1 2 1 - 1 - - -

CO4 3 3 3 1 2 - - - 2 1 - 1 - - -

CO5 3 3 3 1 2 - - 1 2 1 - 1 - - -

CO6 2 3 3 - 3 - - 1 2 2 - 3 - - -

CO 2.83 2.83 3.00 1.00 2.00 - - 1.00 2.00 1.17 - 1.33 - - -

Correlation Level
1. Slight (Low)
2. Moderate (Medium)
3. Substantial (High) ,
If there is no correlation, put “-“.

12
7. LECTURE PLAN
Sl. Taxono
No. of. Proposed Actual Pertaining Mode of
No Topics my
Periods Date Date CO Delivery
. Level

As Per As Per
MD 1,
1 Custom Hooks 1 Academic Academic CO5, CO6 K3
MD 4
Calendar Calendar

HTTP - Fetch, As Per As Per


MD 1,
2 Axios, and Context 1 Academic Academic CO5, CO6 K3
MD 4
API Calendar Calendar
As Per As Per
MD 1,
3 Services 1 Academic Academic CO5, CO6 K3
MD 4
Calendar Calendar

As Per As Per
Behaviour Subjects MD 1,
4 1 Academic Academic CO5, CO6 K3
- StateLess MD 4
Calendar Calendar

StateFulll and As Per As Per


MD 1,
5 Container 1 Academic Academic CO5, CO6 K3
MD 4
Components Calendar Calendar

As Per As Per
Error Handling - MD 1,
6 1 Academic Academic CO5, CO6 K3
Build, Env, CORS MD 4
Calendar Calendar
Unit Testing w As Per As Per
MD 1,
7 React Testing 1 Academic Academic CO5, CO6 K3
MD 4
Library Calendar Calendar
As Per As Per
Introduction to MD 1,
8 1 Academic Academic CO5, CO6 K3
react-native MD 4
Calendar Calendar
As Per As Per
Introduction to MD 1,
9 1 Academic Academic CO5, CO6 K3
StoryBook MD 4
Calendar Calendar

10 As Per As Per
- Lab Exercises 6 Academic Academic CO5, CO6 K3 Iamneo
15 Calendar Calendar

* MD1 – Oral Presentation


* MD 4 – Hands on using any IDE
8. Activity Based Learning

Common Activities

Learning Methods Activities

Class Exercises, Challenge Yourself,


Learn by Solving Problems Practice At Home exercises posted in
iamneo Portal

Knowledge Check / MCQ Using


Learn by Questioning
iamneo portal and RMK Nextgen App

Learn by Hands on Practice available in iamneo Portal

Unit V Activity : - Mind Map Diagram

➢ The basic idea is that the game will present the user with a grid of randomly appearing

balloons, and the objective is to pop them to earn points. Each successful balloon pop will

reward the player with five points:

Check out this live CodePen demo (https://codepen.io/c99rahul/full/GRwQvZY) to preview

what you will build. Or, explore the complete code from the GitHub repo of this project.

(https://github.com/c99rahul/pop-a-balloon)
9. Lecture Notes
Unit 5
REACT LIBRARY - II

Custom Hooks, HTTP - Fetch, Axios, and Context API, Services, Behaviour
Subjects - StateLess, StateFulll and Container Components, Error Handling -
Build, Env, CORS, Unit Testing w React Testing Library - Introduction to react-
native - Introduction to StoryBook

17
9. Lecture Notes – REACT LIBRARY - II
CUSTOM HOOKS

❑ Hooks are a new addition in React 16.8. They let you use state and other React features

without writing a class. Building your own Hooks lets you extract component logic into

reusable functions.

❑ Hooks are reusable functions.

❑ When you have component logic that needs to be used by multiple components, we can

extract that logic to a custom Hook.

❑ Custom Hooks start with "use". Example: useFetch.

❑ Build a Hook

❑ In the following code, we are fetching data in our Home component and displaying it.

❑ We will use the JSONPlaceholder service to fetch fake data. This service is great for testing

applications when there is no existing data.

❑ Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the

page:

import { useState, useEffect } from "react";

import ReactDOM from "react-dom/client";

const Home = () => {

const [data, setData] = useState(null);

useEffect(() => { f

etch("https://jsonplaceholder.typicode.com/todos")

.then((res) => res.json())

.then((data) => setData(data)); }, []);


return (

<>

{data && data.map((item) => { return <p key={item.id}>{item.title}</p>;

})}

</> ); };

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Home />);

❑ The fetch logic may be needed in other components as well, so we will extract that into a

custom Hook.

❑ Move the fetch logic to a new file to be used as a custom Hook:

useFetch.js:

import { useState, useEffect } from "react";

const useFetch = (url) => {

const [data, setData] = useState(null);

useEffect(() => {

fetch(url) .then((res) => res.json())

.then((data) => setData(data)); }, [url]); return [data]; };

export default useFetch;

index.js:

import ReactDOM from "react-dom/client";

import useFetch from "./useFetch";

const Home = () => {

const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");


return (

<>

{data && data.map((item) => { return <p key={item.id}>{item.title}</p>;

})}

</>

); };

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Home />);

Explanation:

We have created a new file called useFetch.js containing a function

called useFetch which contains all of the logic needed to fetch our data.

We removed the hard-coded URL and replaced it with a url variable that can

be passed to the custom Hook.

Lastly, we are returning our data from our Hook.

In index.js, we are importing our useFetch Hook and utilizing it like any

other Hook. This is where we pass in the URL to fetch data from.

Now we can reuse this custom Hook in any component to fetch data from

any URL.

Hooks are a new addition in React 16.8. They let you use state and other

React features without writing a class.

Building your own Hooks lets you extract component logic into reusable

functions.
o When we were learning about using the Effect Hook, we saw this component from a chat
application that displays a message indicating whether a friend is online or offline:
import React, { useState, useEffect } from 'react’;
function FriendStatus(props)
{
const [isOnline, setIsOnline] = useState(null); useEffect(() =>
{
function handleStatusChange(status)
{
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id,
handleStatusChange);
};
});
if (isOnline === null)
{
return 'Loading...’;
}
return isOnline ? 'Online' : 'Offline’;
}
our chat application also has a contact list, and we want to render names of online users with
a green color. We could copy and paste similar logic above into our FriendListItem component
but it wouldn’t be ideal:
import React, { useState, useEffect } from 'react’;

function FriendListItem(props) {

const [isOnline, setIsOnline] = useState(null);

useEffect(() => { function handleStatusChange(status) {

setIsOnline(status.isOnline); }

ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);

return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id,

handleStatusChange); }; });

return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name}

</li> );

❑ Instead, we’d like to share this logic between FriendStatus and FriendListItem.

❑ Traditionally in React, we’ve had two popular ways to share stateful logic between

components: render props and higher-order components. We will now look at how Hooks

solve many of the same problems without forcing you to add more components to the tree.

Extracting a Custom Hook

❑ When we want to share logic between two JavaScript functions, we extract it to a third

function. Both components and Hooks are functions, so this works for them too!

❑ A custom Hook is a JavaScript function whose name starts with ”use” and that may call other

Hooks.

❑ For example, useFriendStatus below is our first custom Hook:


import { useState, useEffect } from 'react’;

function useFriendStatus(friendID)

const [isOnline, setIsOnline] = useState(null);

useEffect(() => {

function handleStatusChange(status) {

setIsOnline(status.isOnline); }

ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);

return () => { ChatAPI.unsubscribeFromFriendStatus(friendID,

handleStatusChange); }; });

return isOnline;

❑ There’s nothing new inside of it — the logic is copied from the components above. Just like

in a component, make sure to only call other Hooks unconditionally at the top level of your

custom Hook.

❑ Unlike a React component, a custom Hook doesn’t need to have a specific signature. We

can decide what it takes as arguments, and what, if anything, it should return. In other

words, it’s just like a normal function. Its name should always start with use so that you can

tell at a glance that the rules of Hooks apply to it.

❑ The purpose of our useFriendStatus Hook is to subscribe us to a friend’s status. This is why

it takes friendID as an argument, and returns whether this friend is online:

function useFriendStatus(friendID) {

const [isOnline, setIsOnline] = useState(null);

// ... return isOnline; }


function FriendStatus(props) {

const isOnline = useFriendStatus(props.friend.id);

if (isOnline === null) {

return 'Loading...'; }

return isOnline ? 'Online' : 'Offline'; }

function FriendListItem(props) {

const isOnline = useFriendStatus(props.friend.id);

return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name}

</li> ); }

❑ Is this code equivalent to the original examples? Yes, it works in exactly the same way. If

you look closely, you’ll notice we didn’t make any changes to the behavior. All we did was to

extract some common code between two functions into a separate function. Custom Hooks

are a convention that naturally follows from the design of Hooks, rather than a React

feature.

5.1. FETCH AND AXIOS


❑ Axios is an HTTP client library that allows you to make requests to a given endpoint:

❑ This could be an external API or your own backend Node.js server, for example.

❑ By making a request, you expect your API to perform an operation according to the request

you made.

❑ For example, if you make a GET request, you expect to get back data to display in your

application.
❑ Axios has better error handling. Axios throws 400 and 500 range errors for you. Unlike the

Fetch API, where you have to check the status code and throw the error yourself.

❑ Axios can be used on the server as well as the client. If you are writing a Node.js

application, be aware that Axios can also be used in an environment separate from the

browser.

How to Set Up Axios with React

Using Axios with React is a very simple process. You need three things:

1. An existing React project

2. To install Axios with npm/yarn

3. An API endpoint for making requests

The quickest way to create a new React application is by going to react.new.

If you have an existing React project, you just need to install Axios with npm (or any other

package manager):

npm install axios

Here is a list of all the different routes you can make requests to, along with the appropriate
HTTP method for each:
How to Make a GET Request

To fetch data or retrieve it, make a GET request.

First, you're going to make a request for individual posts. If you look at the endpoint, you are

getting the first post from the /posts endpoint:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts/1";

export default function App() {

const [post, setPost] = React.useState(null);

React.useEffect(() => {

axios.get(baseURL).then((response) => { setPost(response.data); }); }, []);

if (!post) return null; return (

<div>

<h1>{post.title}</h1>

<p>{post.body}</p>

</div>

❑ To perform this request when the component mounts, you use the useEffect hook. This

involves importing Axios, using the .get() method to make a GET request to your endpoint,

and using a .then() callback to get back all of the response data.

❑ The response is returned as an object. The data (which is in this case a post with id, title,

and body properties) is put in a piece of state called post which is displayed in the component.

❑ Note that you can always find the requested data from the .data property in the response.
How to Make a POST Request

To create new data, make a POST request.

According to the API, this needs to be performed on the /posts endpoint. If you look at the

code below, you'll see that there's a button to create a post:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export default function App()

const [post, setPost] = React.useState(null);

React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => {

setPost(response.data); }); }, []);

function createPost() {

axios .post(baseURL, { title: "Hello World!", body: "This is a new post." })

.then((response) => { setPost(response.data); }); }

if (!post) return "No post!" return ( <div> <h1>{post.title}</h1>

<p>{post.body}</p>

<button onClick={createPost}>Create Post</button> </div> );

❑ When you click on the button, it calls the createPost function.

❑ To make that POST request with Axios, you use the .post() method. As the second

argument, you include an object property that specifies what you want the new post to be.
Once again, use a .then() callback to get back the response data and replace the first post you

got with the new post you requested.

This is very similar to the .get() method, but the new resource you want to create is provided as

the second argument after the API endpoint.

How to Make a PUT Request

To update a given resource, make a PUT request.

In this case, you'll update the first post.

To do so, you'll once again create a button. But this time, the button will call a function to

update a post:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export default function App() {

const [post, setPost] = React.useState(null); React.useEffect(() => {

axios.get(`${baseURL}/1`).then((response) => { setPost(response.data); }); }, []);

function updatePost() {

axios .put(`${baseURL}/1`, { title: "Hello World!", body: "This is an updated post." })

.then((response) => { setPost(response.data); }); }

if (!post) return "No post!" return ( <div> <h1>{post.title}</h1>

<p>{post.body}</p> <button onClick={updatePost}>Update Post</button>

</div> ); }

❑ In the code above, you use the PUT method from Axios. And like with the POST method, you

include the properties that you want to be in the updated resource.

❑ Again, using the .then() callback, you update the JSX with the data that is returned.
How to Make a DELETE Request

Finally, to delete a resource, use the DELETE method.

As an example, we'll delete the first post.

Note that you do not need a second argument whatsoever to perform this request:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export default function App()

const [post, setPost] = React.useState(null);

React.useEffect(() => {

axios.get(`${baseURL}/1`).then((response) => { setPost(response.data); }); }, []);

function deletePost() { axios .delete(`${baseURL}/1`) .then(() => { alert("Post deleted!");

setPost(null) }); }

if (!post)

return "No post!"

return (

<div> <h1>{post.title}</h1> <p>{post.body}</p>

<button onClick={deletePost}>Delete Post</button> </div> );}

❑ In most cases, you do not need the data that's returned from the .delete() method.

❑ But in the code above, the .then() callback is still used to ensure that your request is

successfully resolved.

❑ In the code above, after a post is deleted, the user is alerted that it was deleted successfully.

Then, the post data is cleared out of the state by setting it to its initial value of null.

❑ Also, once a post is deleted, the text "No post" is shown immediately after the alert message.
5.2. STATEFUL AND STATELESS COMPONENTS

State

A State is an object inside the constructor method of a class which is a must in the stateful

components. It is used for internal communication inside a component. It allows you to

create components that are interactive and reusable. It is mutable and can only be changed

by using setState() method.

Simple Example of Stateful Component which has two properties.

import React, { Component } from 'react’;

class StateExample extends Component {

constructor(){

super();

this.state={ first_name: '', last_name: '' } }

render(){

<div><p>State Component </p></div> }}

export default StateExample;

Components

A React application is divided into smaller molecules, and each molecule represents a

component. In other words, a component is the basic building of a React application. It can

be either a class component or a functional component.

React components are independent and reusable and contains JSX(JavaScript XML Syntax)

which a combination of JS + HTML. It may take props as the parameter and returns a

Document Object Model(DOM) element that describes how the User Interface(UI) should

appear.
Class Component(Stateful)

import React, { Component } from 'react';

class StateExample extends Component {

constructor(){ super();

this.state={ first_name: 'Shruti', last_name: 'Priya' } }

render(){

return (

<div> <p> Class Component </p>

<p>{this.state.first_name}</p>

<p>{this.state.last_name}</p> </div>

}}

export default StateExample;

Functional Component(Stateless)

import React from 'react';

function Example(props)

return

<div>

<p>{props.first_name}</p>

<p>{props.last_name}</p>

</div>

)}

export default Example;


Stateful Components

Stateful components are those components which have a state. The state gets initialized in the

constructor. It stores information about the component’s state change in memory. It may get

changed depending upon the action of the component or child components.

Stateless Components

Stateless components are those components which don’t have any state at all, which means you

can’t use this.setState inside these components. It is like a normal function with no render

method. It has no lifecycle, so it is not possible to use lifecycle methods such

as componentDidMount and other hooks. When react renders our stateless component, all that

it needs to do is just call the stateless component and pass down the props.

Stateful vs. Stateless

❑ A stateless component can render props, whereas a stateful component can render both

props and state. A significant thing to note here is to comprehend the syntax distinction. In

stateless components, the props are displayed like {props.name} but in stateful components,

the props and state are rendered like {this.props.name} and {this.state.name} respectively. A

stateless component renders output which depends upon props value, but a stateful

component render depends upon the value of the state. A functional component is always a

stateless component, but the class component can be stateless or stateful.

❑ There are many distinct names to stateful and stateless components.

❑ Container components vs Presentational components

❑ Smart components vs Dumb components

❑ State and Props used in stateful component

import React, { Component } from 'react’;

class StateAndProps extends Component {


constructor(props){
super(props);
this.state={ value: '50' } }
render(){
return (
<div>
<p>{this.state.value}</p>
<p>{this.props.value}</p>
</div>
) }}
export default StateAndProps;
5.3) WHAT ARE CONTAINER AND PRESENTATIONAL COMPONENTS?
To achieve a separation of concerns we have two types of components:
❑ Container components
❑ Presentational components
Container components
❖ These are the components that provide, create, or hold data for the children components.
❖ The only job of a container component is to handle data. It does not consist of any UI of its
own. Rather, it consists of presentational components as its children that uses this data.
❖ A simple example would be a component named FetchUserContainer that consists of some
logic that fetches all the users.
Presentational components
❖ These are the components whose primary responsibility is to present the data on the UI.
They take in the data from the container components.
❖ These components are stateless unless they need their own state for rendering the UI. They
do not alter the data that they receive.
❖ An example of this would be a UserList component that displays all the users.
Why Do We Need These Components?
import { useEffect, useState } from "react";
interface Post { userId: number; id: number; title: string; body: string; }
/** * An example of how we shouldn't combine the logic and presentation of
data. */
export default function DisplayPosts() {
const [posts, setPosts] = useState<Post[] | null>(null);
const [isLoading, setIsLoading] = useState<Boolean>(false);
const [error, setError] = useState<unknown>();
// Logic
useEffect(() => {
(async () => { try { setIsLoading(true);
const resp = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await resp.json();
setPosts(data);
setIsLoading(false);
}
catch (err)
{
setError(err);
setIsLoading(false);
} })(); }, []); // Presentation
return isLoading ? ( <span>Loading... </span> ) : posts ? ( <ul>
{posts.map((post: Post) => ( <li key={`item-${post.id}`}>
<span>{post.title}</span> </li> ))} </ul> ) : (
<span>{JSON.stringify(error)}</span> ); }
Here is what this component does:
It has 3 state variables: posts, isLoading, and error.
We have a useEffect hook that consists of the business logic. Here we are fetching the data
from the
API: [https://jsonplaceholder.typicode.com/posts](https://jsonplaceholder.typicode.com/posts)
with the fetch API.
We make sure that when the data is fetched, we store it in the posts state variable
using setPosts.
We also make sure that we toggle the isLoading and error values during the respective
scenarios.
We put this entire logic inside an async IIFE.
Finally, we return the posts in the form of an unordered list and map through all the posts that
we fetched earlier.
5.4) ERROR HANDLING
A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem for
React users, React 16 introduces a new concept of an “error boundary”.
Error boundaries are React components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of the component tree that
crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in
constructors of the whole tree below them.
A class component becomes an error boundary if it defines a new lifecycle method
called componentDidCatch(error, info):
class ErrorBoundary extends React.Component {
constructor(props) {
super(props); this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service logErrorToMyService(error, info); }
render() {
if (this.state.hasError) { // You can render any custom fallback UI return
<h1>Something went wrong.</h1>; }
return this.props.children; } }
Then you can use it as a regular component:
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
The componentDidCatch() method works like a JavaScript catch {} block, but for components.
Only class components can be error boundaries. In practice, most of the time you’ll want to
declare an error boundary component once and use it throughout your application.
Note that error boundaries only catch errors in the components below them in the tree. An
error boundary can’t catch an error within itself. If an error boundary fails trying to render the
error message, the error will propagate to the closest error boundary above it. This, too, is
similar to how catch {} block works in JavaScript.
Where to Place Error Boundaries
The granularity of error boundaries is up to you. You may wrap top-level route components to
display a “Something went wrong” message to the user, just like server-side frameworks
often handle crashes. You may also wrap individual widgets in an error boundary to protect
them from crashing the rest of the application.
New Behavior for Uncaught Errors
This change has an important implication. As of React 16, errors that were not caught by any
error boundary will result in unmounting of the whole React component tree.
This change means that as you migrate to React 16, you will likely uncover existing crashes in
your application that have been unnoticed before. Adding error boundaries lets you provide
better user experience when something goes wrong.
For example, Facebook Messenger wraps content of the sidebar, the info panel, the
conversation log, and the message input into separate error boundaries. If some component
in one of these UI areas crashes, the rest of them remain interactive.
Component Stack Traces
React 16 prints all errors that occurred during rendering to the console in development, even
if the application accidentally swallows them. In addition to the error message and the
JavaScript stack, it also provides component stack traces. Now you can see where exactly in
the component tree the failure has happened:
5.5) UNIT TESTING & REACT TESTING LIBRARY
When you're building a website and coding all the cool features you had planned, you'll want to
test if everything works as expected.
Now, you can’t do that just by going through the website yourself – you need to check if each
unit of your code is working as you want. For that, you need to write unit tests. And they can
be quite a hassle when you actually get down to writing them.

How Is a Test Structured?


Testing involves checking if your code is functioning as it's supposed to by comparing the
expected output with the actual output.

What to Test
In general, your tests should cover the following aspects of your code:
❑ If a component renders with or without props
❑ How a component renders with state changes
❑ How a component reacts to user interactions

What Not to Test


Testing most of your code is important, but here are some things you do not need to test:
Actual Implementation: You do not need to test the actual implementation of a
functionality. Just test if the component is behaving correctly.
Let’s say you want to sort an array on the click of a button. There’s no need to test the actual
sorting logic. You only test if the function was called and if the state changes are rendering
correctly.
Third Party libraries: If you are using any third party libraries like Material UI, no need to
test those – they should already be tried and tested.

Any test in React, no matter how complicated, follows this structure:


1. Render the component
2. Get an element from the component and simulate any user interactions
3. Write an assertion.
How to Set Up Our Project
First, create the app with create-react-app. We’ll be using Jest and React Testing Library.
Both of them come pre - installed with create-react-app. You can see what it looks like here:

"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1", “
web-vitals": "^2.1.4"
},

As you can see, Jest is not visible here. But, if you go to the node_modules folder, you will
see Jest there. So, no need to install it separately.
Also, make sure you have the following lines in your setupTests.js file:
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';
Also, in your package.json file, modify your scripts like this:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --watchAll --coverage", “
eject": "react-scripts eject"
},
This will run your tests in watch mode and also show you the coverage (that is, the portion
of the code covered by your tests). You can also define the coverage threshold by adding
another property jest. For now, keep the threshold at 80%.
"jest": {
"coverageThreshold":
{
"global": {
"lines": 80
}}}
That’s it, now you are ready to start testing. Let’s first start with a basic test.
How to Write Your First Test for a React App
Let’s write a test for the following component:
const FirstTest = () => {
return (
<div>
<h2> First test </h2>
</div>
)
}
Here, we just need to test if the h2 element renders. Now, where should we write the tests?
We can write them inside a __tests__ folder anywhere in the src folder. The test file just
needs to have a .test.js/jsx extension and the test runner will pick it up.
This is how the test looks in our FirstTest.test.jsx file:
import { render, screen } from '@testing-library/react’
import FirstTest from '../components/FirstTest';
test("Example 1 renders successfully", () => {
render(<FirstTest/>);
const element = screen.getByText(/first test/i);
expect(element).toBeInTheDocument();
})
✓ First, import the required methods. The test() method contains an individual test. It takes
the name of the test and a callback function as the two arguments.
✓ Now, following the structure mentioned above, render the component you're testing using
the render method. Then, use the screen object to make a query for an element. In this
case, it’s the h2 element. Our query gets an element containing text that matches the
regex /first test/i (i means ignore case).
✓ Lastly, make the assertion using the expect method. We expect the element to be in the
document and it is, so the test passes.
✓ There are lots of other assertions you can make in your tests. Also, you can find a list of
ways to query an element from website. We’ll use some of them in our further examples.
How to Test With Mock Data in React
Here, we have a component with a prop data that displays a list of items. Let’s assume this
data comes from the backend and your component is displaying this data.

import React from 'react'


const TestWithMockData = ({data}) => {
return (
<div>
<ul>
{data.map(item => (
<li key={item.id}> {item.id} {item.first_name}, {item.last_name}, {item.email}
</li>
))}
</ul>
</div>
)}
export default TestWithMockData
While writing tests for a component with props, you need to pass some mock data while
rendering this component that pertains to your functionality. Here, one object in our data
contains four fields, so we pass some mock data here.
const mockData = [
{
"id": 1,
"first_name": "Fletcher",
"last_name": "McVanamy",
"email": "[email protected]",
"age": 30
},
{
"id": 2,
"first_name": "Clarice",
"last_name": "Harrild",
"email": "[email protected]",
"age": 35 }, ]
Note that the actual data could contain thousands of records, but the mock data only needs to
be relevant to what you want to test. Now, let’s write the test and check if the list renders.

test("List renders successfully", () => {


render(
<TestWithMockData data={mockData} />
)
expect(screen.getByText(/fletcher/i)).toBeInTheDocument();
})
How to Test With Mock Data Covering All Branches in React

Let’s introduce some branching in the above component. We’ll have another
prop, displayUnorderedList, that determines whether to display an ordered or unordered list.
We’ll also render Senior for age > 50 and Not Senior otherwise.
import React from 'react'
const TestWithMockData = (
{
data, displayUnorderedList, handleClick}) => {
return (
<div>
{displayUnorderedList ?
<ul>
{
data.map(item => (
<li key={item.id}>
{item.id}
{item.first_name},
{item.last_name},
<a onClick={() => { console.log("email link clicked") handleClick() }}>{item.email}</a>
{item.age > 50 ? 'Senior' : 'Not senior'}
</li>
))}
</ul>
:
<ol>
{data.map(item => (
<li key={item.id}>
Last name: {item.last_name}
</li>
))}
</ol>
}
</div>
)}
export default TestWithMockData

Failed Test: Unable to find the element


• You can see that Line 9 (that is, the unordered list part) is not covered by our existing
tests. And our previous test has also failed since it is unable to find fletcher in the
component.
• Why is this so? In our previous test, we have not passed the displayUnorderedList prop to
the component so it is null. So, the component renders the ordered list and it does not
contain the first_name.
• So, let’s write another test covering the ordered list part.

test("Ordered list renders", () => {


render(
<TestWithMockData data={mockData}
displayUnorderedList={false} />
)
expect(screen.getByText(/McVanamy/i)).toBeInTheDocument()
})
Here, pass the prop’s value as false to render the ordered list. Also, add
the displayUnorderedList prop to the failing test and pass the value true.
Now, all our tests pass with 100% coverage.

Uncovered Branch
One line is still not covered by the test cases, which is the branching logic for age. So, add
another record to the mock data that has an age greater than 50.

{ "id": 3,
"first_name": "Amby",
"last_name": "Emmer",
"email": "[email protected]",
"age": 67
}
Now, all our tests should pass with 100% coverage.

How to Test User Interactions in React


▪ The most important part of testing any UI app is testing its behaviour with various user
interactions. Almost every functionality in a UI app involves user interactions.
▪ You can use the user-event library to simulate user interactions. It has methods for
simulating various user events such as click, type, hover, and so on.
▪ First, we need to install the library:
▪ npm install --save-dev @testing-library/user-event
▪ We can use this library to simulate user events. In our examples, we’ll interact with
different elements, mostly input and button elements.

5.6) INTRODUCTION TO REACT-NATIVE

Many different kinds of people use React Native: from advanced iOS developers to React
beginners, to people getting started programming for the first time in their career.
React Native: It is a framework developed by Facebook for creating native-style apps for
iOS & Android under one common language, JavaScript. Initially, Facebook only developed
React Native to support iOS. However, with its recent support of the Android operating
system, the library can now render mobile UIs for both platforms.
What is React Native?
➢ React Native (also known as RN) is a popular JavaScript-based mobile app framework that
allows you to build natively-rendered mobile apps for iOS and Android. The framework lets
you create an application for various platforms by using the same
codebase.
➢ React Native was first released by Facebook as an open-source project in 2015. In just a
couple of years, it became one of the top solutions used for mobile development. React
Native development is used to power some of the world’s leading mobile apps, including
Instagram, Facebook, and Skype. We discuss these and other examples of React Native-
powered apps further in this post.
➢ There are several reasons behind React Native’s global success.
➢ Firstly, by using React Native, companies can create code just once and use it to power
both their iOS and Android apps. This translates to huge time and resource savings.
➢ Secondly, React Native was built based on React – a JavaScript library, which was
already hugely popular when the mobile framework was released.
➢ Thirdly, the framework empowered frontend developers, who could previously only work
with web-based technologies, to create robust, production-ready apps for mobile
platforms.
➢ Interestingly, as with many revolutionary inventions, React Native was developed as a
response to...a big technological mistake.

The history of React Native


❖ When Facebook first decided to make its service available on mobile devices, instead
of building out a native app like many top tech players at the time, they decided to run
with a mobile webpage based on HTML5. However, the solution didn’t stand the test of
time, leaving much room for UI and performance improvements. In fact, in 2012, Mark
Zuckerberg admitted that “the biggest mistake we made as a company was betting too
much on HTML as opposed to native.”
❖ Soon after, in 2013, Facebook developer Jordan Walke made a groundbreaking
discovery – he found a method of generating UI elements for iOS apps by using
JavaScript. This sparked a fire, and a special Hackathon was organized to further
discover how much mobile development could be done using (so far, traditionally web-
based) JavaScript solutions.
❖ That’s how React Native came to life. Initially developed just for iOS, Facebook quickly
followed it up with Android support, before taking the framework public in 2015.
❖ Just three years later, React Native was already the second biggest project on GitHub, as
measured by the number of contributors. In 2019, it stood strong and came sixth, with over
9,100 contributors.

React vs. React Native


✓ In the most simple terms, React Native isn’t a ‘newer’ version of React, although React
Native does use it.
✓ React (also known as ReactJS) is a JavaScript library used for building the frontend of a
website. Similarly to React Native, it was also developed by the Facebook engineering
team.
✓ Meanwhile, React Native – which is powered by React – lets developers use a set of UI
components to quickly compile and launch iOS and Android apps.
✓ Both React and React Native use a mixture of JavaScript and a special markup language,
JSX. However, the syntax used to render elements in JSX components differs between
React and React Native applications. Additionally, React uses some HTML and CSS, whereas
React Native allows the use of native mobile user interface elements.

Setting up the development environment


Installation: Here we will use the Expo CLI version that will much smoother to run your React
Native applications. Follow the below steps one by one to setup your React native
environment.
Step 1: Open your terminal and run the below command.
npm install -g expo-cli
Step 2: Now expo-cli is globally installed so you can create the project folder by running the
below command.
expo init "projectName"
Step 3: Now go into the created folder and start the server by using the following command.
cd "projectName"
npm start web
“React JSX renders HTML-like components like <h1>, <p>, etc. [Meanwhile]
react-native renders native app view components like <View> , <Text>,
<Image>, <ScrollView>, so you can't directly reuse your UI component code
unless you rework/replace all the elements.”

Interactive examples
This introduction lets you get started immediately in your browser with interactive examples
like this one:
import React from 'react';
import {Text, View} from 'react-native';

const YourApp = () => {


return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>You can edit me ! </Text>
</View>
);
};

export default YourApp;


OUTPUT:
You can edit me !
PROJECT STRUCTURE

// File name App.js


import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
const Home=()=>{
return (
<Text style={{
marginTop:300,
marginLeft:10}}>
RMK ENGINEERING COLLEGE
</Text>
)
}
export default function App() {
return (
<View>
<Home/>
</View>
);
}
Advantages over other frameworks and Languages:
❑ Whenever there is an update for apps written in Swift/Objective-C or Java, the whole app
needs to be recompiled and a new version has to be distributed to the App Store again. All
this can take a few weeks depending on the App Store review process.
❑ To avoid this hassle, React Native apps work in a different way, a native app is able to
locate specific JavaScript code, which is later downloaded and compiled when the app is
launched on an actual device. By this, updating the app can be done instantly without
needing to submit a new version to the App Store again and again.
How does React Native work?
Now that we’ve discussed cross-platform development, let’s take a look at the mechanics of
React Native, and how it’s different from anything we’ve seen before.
Don’t worry if you’re not a technical person – we’re going to explain this in layman terms.
As mentioned earlier, React Native is written with a mixture of JavaScript and JXL, a special
markup code resemblant of XML. The framework has the ability to communicate with both
realms – JavaScript-based threads and existent, native app threads.
How does this communication work? React Native uses a so-called “bridge”. While JavaScript
and Native threads are written in completely different languages, it’s the bridge feature that
makes bidirectional communication possible.
Here’s a great visualization of the bridge concept:
What makes React Native unique?

The difference between React Native and other cross-platform development solutions (for
example, Cordova and PhoneGap) is that React Native doesn’t render WebViews in its code. It
runs on actual, native views and components. This is one of the reasons for React Native’s
spectacular success.

Benefits of React Native


Code reusability – cross-platform development
Being able to reuse code is the biggest advantage of React Native, and it indicates that apps
can run effectively on multiple platforms – which is something that CEOs and Product Owners
truly appreciate. They can integrate 90% of the native framework for reusing the code for
both operational systems.
Large developer community
React Native is an open-source JavaScript platform that allows developers to contribute their
knowledge to the framework’s development, which is freely accessible to all.
If any developer experiences a problem while developing an app, then they can turn to the
community for support (as of mid-2020, there are nearly 50,000 active contributors to the
React Native tag in Stack Overflow).
Cost efficiency
Another advantage of React Native development is greater cost efficiency. As mentioned
earlier, this is because developers are able to use the same code to build applications for iOS
and Android.
It means you don’t have to hire two separate iOS and Android dev teams to finalize your
project; a small team is enough to build it. The cost of developing apps in React Native is
much lower than apps built using languages that don’t allow for cross-platform development.
Fast refresh
Fast refresh allows developers to run the app while updating it to new versions and modifying
the UI. Changes are visible immediately, and the developer is spared from rebuilding the
entire app.
This leads to two significant benefits: time savings – as programmers save time on
compilation and increased productivity – since they don’t lose any
state while incorporating changes into the app.
Simple UI
✓ React Native development uses React JavaScript to build the app’s interface, which makes
it more responsive and faster with reduced load time, resulting in an overall better user
experience. Thanks to the reactive UI and component-based approach, the framework is
perfect for building apps with both simple and complex designs.

Fast applications
✓ Some claim that React Native code might have a detrimental effect on an app's
performance. Even though JavaScript code won't run as fast as native code, this difference
is unnoticeable to the human eye. To further prove it, we decided to run a test comparing
two versions of a simple application written in React Native and Swift – both achieved
similar performance results.

Future-proof
✓ Considering the pace at which the framework took over the market and its simple approach
to resolving development problems, the future of React Native for cross-platform apps
looks bright. Even though it has a few disadvantages, which we’ll discuss in the next
section, its speed and convenience of development compensate for them.

REFER THE BELOW LINK FOR SIMPLE REACT NATIVE PROJECT

https://javascript.plainenglish.io/react-native-creating-a-simple-application-298fa0637e72

5.7) INTRODUCTION TO STORY BOOK

Storybook is the most popular UI component development tool for React, Vue, and Angular. It
helps you develop and design UI components outside your app in an isolated environment.
Learn Storybook to create bulletproof UI components, along the way you’ll build an app UI
from scratch.
Set up React Storybook

We'll need to follow a few steps to get the build process set up in our environment. To start
with, we want to use degit to set up our build system. Using this package, you can download
"templates" (partially built applications with some default configuration) to help you fast track
your development workflow.
Let’s run the following commands:
# Clone the template
npx degit chromaui/intro-storybook-react-template taskbox
cd taskbox
# Install dependencies
Yarn
Now we can quickly check that the various environments of our application are working
properly:
# Start the component explorer on port 6006:
yarn storybook
# Run the frontend app proper on port 5173:
yarn dev

Build a simple component


We’ll build our UI following a Component-Driven Development (CDD) methodology. It’s a
process that builds UIs from the “bottom-up”, starting with components and ending with
screens. CDD helps you scale the amount of complexity you’re faced with as you build out the
UI.
Task is the core component of our app. Each task displays slightly differently depending on
exactly what state it’s in. We display a checked (or unchecked) checkbox, some information
about the task, and a “pin” button, allowing us to move tasks up and down the list. Putting
this together, we’ll need these props:
title – a string describing the task
state - which list is the task currently in, and is it checked off?
Get set up
First, let’s create the task component and its accompanying story
file: src/components/Task.jsx and src/components/Task.stories.jsx.

We’ll begin with a baseline implementation of the Task, simply taking in the attributes we
know we’ll need and the two actions you can take on a task (to move it between lists):
import React from 'react';
export default function Task(
{
task: { id, title, state }, onArchiveTask, onPinTask })
{
return (
<div className="list-item">
<label htmlFor="title" aria-label={title}>
<input type="text" value={title} readOnly={true} name="title" />
</label>
</div>
); }
Above, we render straightforward markup for Task based on the existing HTML structure of
the Todos application.
Below we build out Task’s three test states in the story file:

import Task from './Task';


export default {
component: Task,
title: 'Task',
tags: ['autodocs'],
};
export const Default = {
args: { task: { id: '1', title: 'Test Task', state: 'TASK_INBOX', },
}, };
export const Pinned = {
args: { task: { ...Default.args.task, state: 'TASK_PINNED', },
}, };
export const Archived = {
args: { task: { ...Default.args.task, state: 'TASK_ARCHIVED', },
}, };

❑ There are two basic levels of organization in Storybook: the component and its child
stories. Think of each story as a permutation of a component. You can have as many
stories per component as you need.
Component
Story
Story
Story
❑ To tell Storybook about the component we are documenting and testing, we create
a default export that contains:
❑ component -- the component itself
❑ title -- how to group or categorize the component in the Storybook sidebar
❑ tags -- to automatically generate documentation for our components
❑ To define our stories, we'll use Component Story Format 3 (also known as CSF3 ) to build
out each of our test cases. This format is designed to build out each of our test cases in a
concise way. By exporting an object containing each component state, we can define our
tests more intuitively and author and reuse stories more efficiently.
❑ Arguments or args for short, allow us to live-edit our components with the controls addon
without restarting Storybook. Once an args value changes, so does the component.
❑ When creating a story, we use a base task arg to build out the shape of the task the
component expects. Typically modeled from what the actual data looks like. Again, export-
ing this shape will enable us to reuse it in later stories, as we'll see.
10. ASSIGNMENT – 1 To 5
1) Facebook Ads and React Native : (CO5,CO6,K3)
The social networking platform isn’t the only React Native application that was developed
under Facebook’s roof. Facebook Ads was actually the first React Native app for Android and,
the first fully React Native based, cross-platform app built in the company.
The framework seemed perfectly suitable for the lot of complex business logic required to
accurately handle differences in ad formats, time zones, date formats, currencies, currency
conventions, and so on, especially that a big chunk of it was already written in JavaScript.
On top of that, implementation of UI surfaces with much data would be much easier with
React Native.
Numerous components developed alongside with the Facebook Ads app have been useful for
other developers in building their apps.
Read more about the first fully React Native app from Facebook.

2) Instagram and React Native (CO5,CO6,K3)


Instagram took the challenge to integrate React Native into their existing native app starting
from the simplest view you can imagine: the Push Notifications view which was originally
implemented as the WebView. It didn’t require building navigation infrastructure, as UI was
quite simple.
The dev team at Instagram faced a few problems on the way, but they substantially improved
developer velocity. 85% to 99% of code was shared between Android and iOS apps,
depending on products, thus the team was able to deliver the app much faster than they
would have with a native solution.
10. ASSIGNMENT – 1 To 5
3) Shine and React Native (CO5,CO6,K3)
Shine is a mindfulness app that lets users read motivational mottos and articles, helps them
relax and "check in" for the day, offers inspiring recordings created by experts, and helps deal
with the stresses of everyday life.
The creators wanted to develop the app for iOS devices first, as their target was the U.S.
market, where iOS has a significant market share (44.8% as of December 2018). However,
they wanted to be able to quickly build an Android app once the business gets traction. That’s
why they chose React Native.
The app was successfully launched in December 2017, and it’s already been featured in the
App Store. What is more, it has been chosen by Apple as one of the best apps of 2018. You
can read more about Shine’s success story here.
Read more about the first fully React Native app from Facebook.

4) Uber Eats and React Native (CO5,CO6,K3)

Uber has recently shared their insights about leveraging React Native in engineering
of their food delivery app. Unlike the standard Uber app, Uber Eats marketplace involves
three parties: restaurants, delivery-partners and eaters. Such model required an extra
dashboard for restaurants.
The original Restaurant Dashboard was built for the web and it provided limited access to
the native device functionalities, such as sound notifications which was
a crucial problem for user experience.
10. ASSIGNMENT – 1 To 5
As the team had a great deal of experience using React but limited iOS/Android exposure
they decided to rebuild the dashboard with RN.
Although the framework constitutes only a small part of technology stack used in Uber
Eats, developers are very positive about its possibilities and capacity that can help them
meet needs as the marketplace grows.

5) Tesla and React Native (CO5,CO6,K3)


Tesla, the world’s famous producer of electric cars, has also joined the React Native
community. The company developed its application for electric car and Powerwall battery
owners using Facebook’s trending framework. The app is designed to diagnose and locate a
vehicle, as well as partially control it with the help of a smartphone.
Tesla hasn’t unveiled many details about the project, but the app has received overall
positive feedback from customers.
11. PART A : Questions & Answers
1. What is Custom Hooks (CO5,K2)
❑ Hooks are a new addition in React 16.8. They let you use state and other React features

without writing a class. Building your own Hooks lets you extract component logic into

reusable functions.

❑ Hooks are reusable functions.

❑ When you have component logic that needs to be used by multiple components, we can

extract that logic to a custom Hook.

❑ Custom Hooks start with "use". Example: useFetch.

❑ Build a Hook

❑ In the following code, we are fetching data in our Home component and displaying it.

❑ We will use the JSONPlaceholder service to fetch fake data. This service is great for testing

applications when there is no existing data.

❑ Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the

page:

2. Write the example for custom Hooks (CO5,K2)

import { useState, useEffect } from "react";

import ReactDOM from "react-dom/client";

const Home = () => {

const [data, setData] = useState(null);

useEffect(() => { f

etch("https://jsonplaceholder.typicode.com/todos")

.then((res) => res.json())

.then((data) => setData(data)); }, []);


return (
<>
{data && data.map((item) => { return <p key={item.id}>{item.title}</p>;
})}
</> ); };
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);

3. How to “Extract Custom Hook” (CO5,K2)


❑ When we want to share logic between two JavaScript functions, we extract it to a third
function. Both components and Hooks are functions, so this works for them too!
❑ A custom Hook is a JavaScript function whose name starts with ”use” and that may call
other Hooks. For example, useFriendStatus below is our first custom Hook:
import { useState, useEffect } from 'react’;
function useFriendStatus(friendID) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status)
{ setIsOnline(status.isOnline); }
ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
return () => { ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); }; });
return isOnline; }
4. How to “Use Custom Hook” (CO5,K2)
❑ In the beginning, our stated goal was to remove the duplicated logic from
the FriendStatus and FriendListItem components. Both of them want to
know whether a friend is online.
❑ Now that we’ve extracted this logic to a useFriendStatus hook, we can just use it:
function FriendStatus(props) { c

onst isOnline = useFriendStatus(props.friend.id);

if (isOnline === null) { return 'Loading...'; }

return isOnline ? 'Online' : 'Offline'; }

function FriendListItem(props) {

const isOnline = useFriendStatus(props.friend.id);

return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name} </li> ); }

5. How to fetch and Axios with react and why use AXIOS (CO5,K2)

❑ Axios is an HTTP client library that allows you to make requests to a given endpoint:

❑ This could be an external API or your own backend Node.js server, for example.

❑ By making a request, you expect your API to perform an operation according to the request

you made.

❑ For example, if you make a GET request, you expect to get back data to display in your

application.

❑ Here are five reasons why you should use Axios as your client to make HTTP requests:

❑ It has good defaults to work with JSON data. Unlike alternatives such as the Fetch API, you

often don't need to set your headers. Or perform tedious tasks like converting your request

body to a JSON string.

❑ Axios has function names that match any HTTP methods. To perform a GET request, you

use the .get() method.

❑ Axios does more with less code. Unlike the Fetch API, you only need one .then() callback to

access your requested JSON data.


6. How to setup Axios with react?(CO5,K2)

7. How to make a GET request. (CO5,K2)

To fetch data or retrieve it, make a GET request.

First, you're going to make a request for individual posts. If you look at the endpoint, you are

getting the first post from the /posts endpoint:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts/1";

export default function App() {

const [post, setPost] = React.useState(null);

React.useEffect(() => { axios.get(baseURL).then((response) => {

etPost(response.data); }); }, []);

if (!post) return null; return ( <div> <h1>{post.title}</h1>

<p>{post.body}</p> </div>
❑ To perform this request when the component mounts, you use the useEffect hook. This

involves importing Axios, using the .get() method to make a GET request to your

endpoint, and using a .then() callback to get back all of the response data.

❑ The response is returned as an object. The data (which is in this case a post with id, title,

and body properties) is put in a piece of state called post which is displayed in the

component.

❑ Note that you can always find the requested data from the .data property in the response.

8. How to make a POST request. (CO5,K2)

❑ To create new data, make a POST request.

❑ According to the API, this needs to be performed on the /posts endpoint. If you look at

the code below, you'll see that there's a button to create a post:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export default function App() { const [post, setPost] = React.useState(null);

React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => {

setPost(response.data); }); }, []);

function createPost() { axios .post(baseURL, { title: "Hello World!", body: "This

is a new post." }) .then((response) => { setPost(response.data); }); }

if (!post) return "No post!"

return ( <div> <h1>{post.title}</h1> <p>{post.body}</p>

<button onClick={createPost}>Create Post</button> </div> ); }


❑ When you click on the button, it calls the createPost function.

❑ To make that POST request with Axios, you use the .post() method. As the second

argument, you include an object property that specifies what you want the new post to be.

❑ Once again, use a .then() callback to get back the response data and replace the first post

you got with the new post you requested.

❑ This is very similar to the .get() method, but the new resource you want to create is

provided as the second argument after the API endpoint.

9. How to make a PUT request. (CO5,K2)

❑ To update a given resource, make a PUT request.

❑ In this case, you'll update the first post.

❑ To do so, you'll once again create a button. But this time, the button will call a function to

update a post:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export default function App() { const [post, setPost] = React.useState(null);

React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => {

setPost(response.data); }); }, []);

function updatePost() { axios.put(`${baseURL}/1`, { title: "Hello World!", body:

"This is an updated post." }) .then((response) => { setPost(response.data); });

if (!post) return "No post!"

return ( <div> <h1>{post.title}</h1>

<p>{post.body}</p>

<button onClick={updatePost}>Update Post</button>

</div> ); }
❑ In the code above, you use the PUT method from Axios. And like with the POST method,

you include the properties that you want to be in the updated resource.

❑ Again, using the .then() callback, you update the JSX with the data that is returned.

9. How to make a DELETE request. (CO5,K2)

❑ Finally, to delete a resource, use the DELETE method.

❑ As an example, we'll delete the first post.

❑ Note that you do not need a second argument whatsoever to perform this request:

import axios from "axios";

import React from "react";

const baseURL = "https://jsonplaceholder.typicode.com/posts";

export default function App() {

const [post, setPost] = React.useState(null);

React.useEffect(() => { axios.get(`${baseURL}/1`).then((response) => {

setPost(response.data); }); }, []);

function deletePost() { axios .delete(`${baseURL}/1`) .then(() => { alert("Post

deleted!");

setPost(null) }); }

if (!post)

return "No post!"

return ( <div> <h1>{post.title}</h1> <p>{post.body}</p>

<button onClick={deletePost}>Delete Post</button> </div> );}

❑ In most cases, you do not need the data that's returned from the .delete() method.

❑ But in the code above, the .then() callback is still used to ensure that your request is

successfully resolved.
❑ In the code above, after a post is deleted, the user is alerted that it was deleted

successfully. Then, the post data is cleared out of the state by setting it to its initial value

of null.

❑ Also, once a post is deleted, the text "No post" is shown immediately after the alert

message.

10. What is a State ?(CO5,K2)

State

A State is an object inside the constructor method of a class which is a must in the stateful

components. It is used for internal communication inside a component. It allows you to create

components that are interactive and reusable. It is mutable and can only be changed by using

setState() method.

Simple Example of Stateful Component which has two properties.

import React, { Component } from 'react’;

class StateExample extends Component {

constructor(){

super();

this.state={ first_name: '', last_name: '' } }

render(){

<div><p>State Component </p></div> }}

export default StateExample;

11. What is a Component? (CO5,K2)

Components

A React application is divided into smaller molecules, and each molecule represents a

component. In other words, a component is the basic building of a React application. It can be

either a class component or a functional component.


React components are independent and reusable and contains JSX(JavaScript XML Syntax)

which a combination of JS + HTML. It may take props as the parameter and returns a

Document Object Model(DOM) element that describes how the User Interface(UI) should

appear.

11. What is a Class Component ?(CO5,K2)

Class Component(Stateful)

import React, { Component } from 'react';

class StateExample extends Component {

constructor(){ super();

this.state={ first_name: 'Shruti', last_name: 'Priya' } }

render(){

return (

<div> <p> Class Component </p>

<p>{this.state.first_name}</p>

<p>{this.state.last_name}</p> </div>

) }}

export default StateExample

12. What is a Functional Component ?(CO5,K2)


Functional Component(Stateless)
import React from 'react';
function Example(props)
{
return(
<div>
<p>{props.first_name}</p>
<p>{props.last_name}</p>
</div>
)}export default Example;
13. What is a State & Stateless Component (CO5,K2)

Stateful Components

Stateful components are those components which have a state. The state gets initialized in the

constructor. It stores information about the component’s state change in memory. It may get

changed depending upon the action of the component or child components.

Stateless Components

Stateless components are those components which don’t have any state at all, which means

you can’t use this.setState inside these components. It is like a normal function with no render

method. It has no lifecycle, so it is not possible to use lifecycle methods such

as componentDidMount and other hooks. When react renders our stateless component, all that

it needs to do is just call the stateless component and pass down the props.

14. Mention with example for Stateful & Stateless Component (CO5,K2)

Stateful vs. Stateless

❑ A stateless component can render props, whereas a stateful component can render both

props and state. A significant thing to note here is to comprehend the syntax distinction. In

stateless components, the props are displayed like {props.name} but in stateful

components, the props and state are rendered

like {this.props.name} and {this.state.name} respectively. A stateless component renders

output which depends upon props value, but a stateful component render depends upon the

value of the state. A functional component is always a stateless component, but the class

component can be stateless or stateful.

❑ There are many distinct names to stateful and stateless components.


❑ Container components vs Presentational components

❑ Smart components vs Dumb components

❑ State and Props used in stateful component

import React, { Component } from 'react’;

class StateAndProps extends Component {

constructor(props){

super(props);

this.state={ value: '50' } }

render(){

return (

<div>

<p>{this.state.value}</p>

<p>{this.props.value}</p>

</div>

) }}

export default StateAndProps;

15. What are Container And Presentational Components? (CO5,K2)


To achieve a separation of concerns we have two types of components:
❑ Container components
❑ Presentational components
Container components
❖ These are the components that provide, create, or hold data for the children components.
❖ The only job of a container component is to handle data. It does not consist of any UI of its
own. Rather, it consists of presentational components as its children that uses this data.
❖ A simple example would be a component named FetchUserContainer that consists of some
logic that fetches all the users.
Presentational components
❖ These are the components whose primary responsibility is to present the data on the UI.
They take in the data from the container components.
❖ These components are stateless unless they need their own state for rendering the UI.
They do not alter the data that they receive.
❖ An example of this would be a UserList component that displays all the users.
16. Give an example for Container And Presentational Components? (CO5,K2)
import { useEffect, useState } from "react";
interface Post {
userId: number; id: number; title: string; body: string; }
/** * An example of how we shouldn't combine the logic and presentation of data. */
export default function DisplayPosts() {
const [posts, setPosts] = useState<Post[] | null>(null);
const [isLoading, setIsLoading] = useState<Boolean>(false);
const [error, setError] = useState<unknown>();
// Logic
useEffect(() => {
(async () => { try { setIsLoading(true); const resp = await
fetch("https://jsonplaceholder.typicode.com/posts");
const data = await resp.json(); setPosts(data);
setIsLoading(false); }
catch (err) {
setError(err);
setIsLoading(false); } })(); }, []); // Presentation
return isLoading ? ( <span>Loading... </span> ) : posts ? ( <ul> {posts.map((post: Post)
=> ( <li key={`item-${post.id}`}> <span>{post.title}</span> </li> ))} </ul> ) : (
<span>{JSON.stringify(error)}</span> ); }
17. Why Do We Need Container And Presentational Components? (CO5,K2)
Here is what this component does:
❖ It has 3 state variables: posts, isLoading, and error.
❖ We have a useEffect hook that consists of the business logic. Here we are fetching the
data from the API: [https://jsonplaceholder.typicode.com/posts]
(https://jsonplaceholder.typicode.com/posts) with the fetch API.
❖ We make sure that when the data is fetched, we store it in the posts state variable
using setPosts.
❖ We also make sure that we toggle the isLoading and error values during the respective
scenarios.
❖ We put this entire logic inside an async IIFE.
❖ Finally, we return the posts in the form of an unordered list and map through all the posts
that we fetched earlier.
18. What is Error Handling ?(CO5,K2)
❖ A JavaScript error in a part of the UI shouldn’t break the whole app. To solve this problem
for React users, React 16 introduces a new concept of an “error boundary”.
❖ Error boundaries are React components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of the component tree
that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in
constructors of the whole tree below them.
❖ A class component becomes an error boundary if it defines a new lifecycle method
called componentDidCatch(error, info):
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info)
{
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service logErrorToMyService(error, info); }
render() {
if (this.state.hasError) { // You can render any custom fallback UI
return <h1>Something went wrong.</h1>; }
return this.props.children; }
}
19. Where to Place Error Boundaries. (CO5,K2)
The granularity of error boundaries is up to you. You may wrap top-level route components
to display a “Something went wrong” message to the user, just like server-side frameworks
often handle crashes. You may also wrap individual widgets in an error boundary to protect
them from crashing the rest of the application.
20. Define BUILD, ENV, CORS. (CO5,K2)
The componentDidCatch() method works like a JavaScript catch {} block, but for
components. Only class components can be error boundaries. In practice, most of the time
you’ll want to declare an error boundary component once and use it throughout your
application.
Note that error boundaries only catch errors in the components below them in the tree. An
error boundary can’t catch an error within itself. If an error boundary fails trying to render
the error message, the error will propagate to the closest error boundary above it. This, too,
is similar to how catch {} block works in JavaScript.
20. What is Testing in React (CO5,K2)
When you're building a website and coding all the cool features you had planned, you'll want
to test if everything works as expected.
Now, you can’t do that just by going through the website yourself – you need to check if
each unit of your code is working as you want. For that, you need to write unit tests. And
they can be quite a hassle when you actually get down to writing them.
How Is a Test Structured?
Testing involves checking if your code is functioning as it's supposed to by comparing the
expected output with the actual output.
What to Test
In general, your tests should cover the following aspects of your code:
❑ If a component renders with or without props
❑ How a component renders with state changes
❑ How a component reacts to user interactions
21. What is History of React Native.(CO5,K2)
❖ When Facebook first decided to make its service available on mobile devices, instead
of building out a native app like many top tech players at the time, they decided to run
with a mobile webpage based on HTML5. However, the solution didn’t stand the test of
time, leaving much room for UI and performance improvements. In fact, in 2012, Mark
Zuckerberg admitted that “the biggest mistake we made as a company was betting too
much on HTML as opposed to native.”
❖ Soon after, in 2013, Facebook developer Jordan Walke made a groundbreaking discovery –
he found a method of generating UI elements for iOS apps by using JavaScript. This
sparked a fire, and a special Hackathon was organized to further discover how much mobile
development could be done using (so far, traditionally web-based) JavaScript solutions.
❖ That’s how React Native came to life. Initially developed just for iOS, Facebook quickly
followed it up with Android support, before taking the framework public in 2015.

22. What is React Native? (CO5,K2)


React Native: It is a framework developed by Facebook for creating native-style apps for
iOS & Android under one common language, JavaScript. Initially, Facebook only developed
React Native to support iOS. However, with its recent support of the Android operating
system, the library can now render mobile UIs for both platforms.
React Native (also known as RN) is a popular JavaScript-based mobile app framework that
allows you to build natively-rendered mobile apps for iOS and Android. The framework lets
you create an application for various platforms by using the same codebase.

23. Write an Interactive Example for React native (CO5,K2)


This introduction lets you get started immediately in your browser with interactive examples
like this one:
import React from 'react';
import {Text, View} from 'react-native';
const YourApp = () => {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>You can edit me ! </Text>
</View>
);
};

export default YourApp;


OUTPUT:
You can edit me !
23. Difference between React & React Native. (CO5,K2)

✓ In the most simple terms, React Native isn’t a ‘newer’ version of React, although React
Native does use it.
✓ React (also known as ReactJS) is a JavaScript library used for building the frontend of a
website. Similarly to React Native, it was also developed by the Facebook engineering
team.
✓ Meanwhile, React Native – which is powered by React – lets developers use a set of UI
components to quickly compile and launch iOS and Android apps.
✓ Both React and React Native use a mixture of JavaScript and a special markup language,
JSX. However, the syntax used to render elements in JSX components differs between
React and React Native applications. Additionally, React uses some HTML and CSS, whereas
React Native allows the use of native mobile user interface elements.
24. How do the project structure looks for React Native. (CO5,K2)

25. How does React Native works. (CO5,K2)


▪ Now that we’ve discussed cross-platform development, let’s take a look at the mechanics
of React Native, and how it’s different from anything we’ve seen before.
▪ Don’t worry if you’re not a technical person – we’re going to explain this in layman terms.
▪ As mentioned earlier, React Native is written with a mixture of JavaScript and JXL, a
special markup code resemblant of XML. The framework has the ability to communicate
with both realms – JavaScript-based threads and existent, native app threads.
▪ How does this communication work? React Native uses a so-called “bridge”. While
JavaScript and Native threads are written in completely different languages, it’s the
bridge feature that makes bidirectional communication possible.
Here’s a great visualization of the bridge concept:
26. What are the Benefits of React Native. (CO5,K2)
Code reusability – cross-platform development
✓ Being able to reuse code is the biggest advantage of React Native, and it indicates that apps
can run effectively on multiple platforms – which is something that CEOs and Product
Owners truly appreciate. They can integrate 90% of the native framework for reusing the
code for both operational systems.
Large developer community
✓ React Native is an open-source JavaScript platform that allows developers to contribute their
knowledge to the framework’s development, which is freely accessible to all.
✓ If any developer experiences a problem while developing an app, then they can turn to the
community for support (as of mid-2020, there are nearly 50,000 active contributors to the
React Native tag in Stack Overflow).
Cost efficiency
✓ Another advantage of React Native development is greater cost efficiency. As mentioned
earlier, this is because developers are able to use the same code to build applications for iOS
and Android.
✓ It means you don’t have to hire two separate iOS and Android dev teams to finalize your
project; a small team is enough to build it. The cost of developing apps in React Native is
much lower than apps built using languages that don’t allow for cross-platform development.
Fast refresh
✓ Fast refresh allows developers to run the app while updating it to new versions and
modifying the UI. Changes are visible immediately, and the developer is spared from
rebuilding the entire app.
27. How to setup StoryBook. (CO5,K2)
We'll need to follow a few steps to get the build process set up in our environment. To start
with, we want to use degit to set up our build system. Using this package, you can download
"templates" (partially built applications with some default configuration) to help you fast track
your development workflow.

Let’s run the following commands:


# Clone the template
npx degit chromaui/intro-storybook-react-template taskbox
cd taskbox
# Install dependencies
Yarn
Now we can quickly check that the various environments of our application are working
properly:
# Start the component explorer on port 6006:
yarn storybook
# Run the frontend app proper on port 5173:
yarn dev

28. What is StoryBook. (CO5,K2)

Storybook is the most popular UI component development tool for React, Vue, and Angular. It
helps you develop and design UI components outside your app in an isolated environment.
Learn Storybook to create bulletproof UI components, along the way you’ll build an app UI
from scratch.
29. What makes React Native unique? (CO5,K2)

The difference between React Native and other cross-platform development solutions (for
example, Cordova and PhoneGap) is that React Native doesn’t render WebViews in its code. It
runs on actual, native views and components. This is one of the reasons for React Native’s
spectacular success.
30. How to Get set up Story Book? (CO5,K2)
First, let’s create the task component and its accompanying story
file: src/components/Task.jsx and src/components/Task.stories.jsx.

We’ll begin with a baseline implementation of the Task, simply taking in the attributes we
know we’ll need and the two actions you can take on a task (to move it between lists):
import React from 'react';
export default function Task(
{
task: { id, title, state }, onArchiveTask, onPinTask })
{
return (
<div className="list-item">
<label htmlFor="title" aria-label={title}>
<input type="text" value={title} readOnly={true} name="title" />
</label>
</div>
); }
12. PART B : Questions
Q. CO
Questions K Level
No. Level

1 Explain about Fetch and Axios using RestAPI Data. CO5 K3

Explain how to implement React-Testing Library in


2 CO5 K4
Detail.

3 Explain in detail about Enable HOC and Aux CO5 K4


Components.
Describe in detail about Stateful & Stateless
4 CO5 K3
Components.

Explain how to Implement Unit & React-Testing Library


5 CO5 K4
in Detail.

Explain how to make a GET , PUT, POST, DELETE request


6 CO5 K3
in Axios

Employ back end api for Login Page functionality


(authentication).
Post login, store the user context (received from the
back end server) in browser’s session storage as objects.
7 CO5 K3
And use the same as creds during protected route
verification On the dashboard page, have a grid of
Students. The data has to be bought from back end api.
Employ useref, useeffect & usestate, and useHistory.
Explain in detail about Build Env Cors and Error Handling
8 CO5 K3
in react .
Explain the following in Detail:
1. History of React Native and its project
Structure.
9 2. Benefits of React Native. CO5 K4
3. Compare the difference between React
and React Native.
4. Why is it unique?

Describe the following in Detail:


1. What is Story Book and write the steps for
10 CO5 K3
Setup.

2. Give the get Set up of Story Book with example.


13. SUPPORTIVE ONLINE CERTIFICATION COURSES

• React Basics - coursera

https://www.coursera.org/learn/react-basics

• Udemy: "React - The Complete Guide (incl Hooks,


React Router, Redux)" by Maximilian Schwarzmüller:

• https://www.udemy.com/course/react-the-complete-
guide-incl-redux/learn/

• Edx: "CS50’s Web Programming with Python and


JavaScript" by Harvard University:

• https://cs50.harvard.edu/web/2020/

79
14. REAL TIME APPLICATIONS
1) A WEB APPLICATION PROVIDING RANGE OF OPTIONS TO CAR BUYERS

Car selling website is where the customer can buy and sell their car. This website is
user friendly and ease to use for any customer, it has effective search box to get the
precise and suitable car for the user. A rich search facility is always there from where
customer can search vehicle via category, keywords, price range, brand, types, fuel
types, etc. The website displays information of the customer support person on the
homepage so that user can directly contact them or meet them which help in
decreasing the communication gap. This website also provides a facility for road side
assistance. The social media plugin will help the company to know their popularity over
the social media.

2) PLAY YOUR FANTASY SPORTS ONLINE USING WEB APPLICATION

This application is developed for users who are interested in playing fantasy sports
online. Users can play fantasy sports with close friends or people you met over the
internet. Users can create their own leagues and can invite friends to play in their
league or they can play in others leagues. Users can easily change the league size,
payment deadlines, payout verifications and payout timelines. This system guarantee
the professional safekeeping of the funds through full-featured security measures.
User can withdraw funds from their account. User can refer a friend to play a particular
league.

3) BOOTSTRAP & RESPONSIVE DESIGN

Responsive web design is a way of making a single website that works effectively on
both desktop browsers and the myriad of mobile devices on the market. It involves
having a website that enhances the viewing experience, irrespective of which device is
being used. Bootstrap makes the front-end web development faster and easier. It is
made for the users of all skill levels, devices of all shapes and projects of all sizes. It is
considered the most popular HTML, CSS, and JavaScript framework for developing
responsive & mobile-first websites. With a responsive website design,

80
15. CONTENT BEYOND SYLLABUS
1. Automating Visual Regression Testing
What: Detect unintended visual changes by comparing snapshots of components over
time.
Tools: Integrate tools like Chromatic or Storyshots (part of Jest).
Why: Ensures UI consistency, especially in large projects with many contributors.
Implementation: Reusable Pipeline for User Data Processing.
Example:
Set up Storyshots:
npx storybook init
npm install @storybook/addon-storyshots
Create a test file:
import initStoryshots from '@storybook/addon-storyshots’;
initStoryshots();
2. Managing Complex Component Hierarchies
What: Organize stories to reflect the actual component structure.
How: Use CSF (Component Story Format) and nested folders.
Why: Keeps the Storybook clean and easier to navigate as your project grows.
Example:
export default {
title: 'Components/Forms/LoginForm',
component: LoginForm,
};
3. Storybook Controls and Dynamic PropsWhat: Create dynamic, interactive stories using
Controls.Why: Allows non-developers (like designers) to experiment with props directly in
the UI.
Example:
export default {
title: 'Button',
component: Button,
argTypes: {
backgroundColor: { control: 'color' },
size: { control: { type: 'select', options: ['small', 'medium', 'large'] } },
}, };
const Template = (args) => <Button {...args} />;
export const Primary = Template.bind({}); 81

Primary.args = { label: 'Click Me' };


16. ASSESSMENT SCHEDULE

• Tentative schedule for the Assessment During


2024-2025 Even Semester

Name of the
S.NO Start Date End Date Portion
Assessment
As per schedule after
1 Unit Test 1 UNIT 1
Unit I completion
2 IAT 1 28.01.2025 03.02.2025 UNIT 1 & 2

As per schedule after


3 Unit Test 2 UNIT 3
Unit III completion

4 IAT 2 10.03.2025 15.03.2025 UNIT 3 & 4

5 Model 03.04.2025 17.04.2025 ALL 5 UNITS

163

82
17. PRESCRIBED TEXT BOOKS
&
REFERENCE BOOKS

TEXT BOOKS:
1. Andy Harris, “HTML5 and CSS3 All-in-One For Dummies Book”, 3rd Edition, 2014.
2. David McFarland, “JavaScript and JQuery: Interactive Front-End Web
Development”.
REFERENCES:

1. Robert. W. Sebesta, "Programming the World Wide Web", Pearson Education,

Fourth Edition, 2007 .

2. Deitel, Deitel, Goldberg, "Internet and World Wide Web How To Program",

Pearson Education, Third Edition, 2006.

3. Marty Hall and Larry Brown, “Core Web Programming”, Pearson Education,

Second Edition, Volume I and II, 2001.

4. Bates, “Developing Web Applications”, Wiley, 2006

5. https://www.w3schools.com/js/js_es6.asp

6. http://es6-features.org/

7. https://www.tutorialspoint.com/es6/index.htm

83
18. MINI PROJECT – 1 to 5
1) E-COMMERCE SITE : (CO5,CO6,K5)

An e-commerce site allows users to browse and search for products, add them to a cart,
and check out using a dummy payment system. To build this app, you can create
a Product component that represents a single product and a ProductList component that
contains a list of Product components. The Product component should accept information
about the product, such as its name, price, and image, and render it along with a Add to
cart button. The ProductList component should accept an array of products and render
a Product component for each. You can also create a Cart component that displays the
items in the user’s cart and allows them to remove items or check out.

2) DIARY (CALENDAR) APP: (CO5,CO6,K5)

A calendar app allows users to view, add, and edit events in a calendar. To build this app,
you can create a Calendar component that displays the current month and year and the
days of the week. You can then create an Event component representing a single event and
an EventList component containing a list of Event components. The Event component
should accept information about the event, such as its name, date, and time, and render
this information in a user-friendly way. The EventList component should accept an array of
events and render an Event component for each. You can also add features such as
switching between months and viewing events for specific dates.

3) WEATHER APP : (CO5,CO6,K5)

A weather app shows the current weather for a given location. To build this app, you can
use the OpenWeatherMap API to fetch weather data for a given location. You can then
create a Weather component that accepts a location and displays the current temperature,
humidity, and other relevant information for that location. You can also add a search form
that allows users to enter a location and see the current weather for that location.
18. MINI PROJECT – 1 to 5
4) A RECIPE APP : (CO5,CO6,K5)

A recipe app allows users to search for recipes and save their favorites. To build this app,
you can use the Spoonacular API to fetch recipe data. You can then create
a Recipe component representing a single recipe and a RecipeList component containing a
list of Recipe components. The Recipe component should accept information about the
recipe, such as its name, ingredients, and instructions, and render this information user-
friendly. The RecipeList component should accept an array of recipes and render
a Recipe component for each. You can also add a search form that allows users to enter a
keyword and see a list of matching recipes.

5) A TASK MANAGER APP : (CO5,CO6,K5)

This allows users to create and track tasks, set deadlines, and organize them into different
categories. This project can be implemented using React, React Hooks for state
management, and CSS for styling. To create tasks, students can use the useState hook to
store the list of tasks in the component’s state and render an input field where users can
enter their task description. To set deadlines, students can use the DatePicker component
from the react-datepicker library to allow users to select a date for their task.
Thank you

Disclaimer:

This document is confidential and intended solely for the educational purpose of
RMK Group of Educational Institutions. If you have received this document through
email in error, please notify the system manager. This document contains
proprietary information and is intended only to the respective group / learning
community as intended. If you are not the addressee you should not disseminate,
distribute or copy through e-mail. Please notify the sender immediately by e-mail if
you have received this document by mistake and delete this document from your
system. If you are not the intended recipient you are notified that disclosing,
copying, distributing or taking any action in reliance on the contents of this
information is strictly prohibited.

86

You might also like