Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Module 04 Modern Web Applications

Uploaded by

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

Module 04 Modern Web Applications

Uploaded by

Kumar Subrato
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

Modern web Applications 20CB662

Prerequisites Fundamentals of computer networks


To understand the principles of creating an effective web page
Course
including an in-depth consideration of information
Objectives
architecture.
Module 04 Topics
Back End Technologies:
– Introduction to jQuery - Syntax,
– Selectors,
– Events,
– Traversing,
– AJAX;
Introduction to Bootstrap
– Basics,
– Grids,
– Themes
React JS
– Introduction,
– Class,
– Components,
– Forms,
– Events,
– Conditionals and Lists.
Introduction to jQuery
• jQuery is a lightweight JavaScript Library, and
it simplifies the JavaScript Programming.
• jQuery is easy to learn and can be used to
– Make HTML/DOM manipulation
– Perform CSS manipulation
– Handle HTML event methods
– Create effects and animations
– AJAX
Introduction to JQuery
• Many of the biggest companies on the Web
use jQuery, such as:
– Google
– Microsoft
– IBM
– Netflix
• jQuery will run exactly the same in all major
browsers.
How to add JQuery to your website
• JQuery can be added in two ways
– Download the jQuery library from jQuery.com
• There are two version of JQuery available
– Production version
– Development version
• syntax of including jquery
<head>
<script src="jquery-3.7.1.min.js"></script>
</head>
Preferably save the files in same folder.
– Include JQuery from a CDN
Include JQuery from a CDN
• syntax of including jquery
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/
3.7.1/jquery.min.js"></script>
</head>

• Many users already have downloaded jQuery from


Google when visiting another site. As a result, it
will be loaded from cache when they visit your site,
which leads to faster loading time
jQuery Syntax
• Its possible, to select (query) HTML elements and
perform "actions" on them using Jquery
• syntax is:
$(selector).action( )
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
• Example
– $("p").hide() //hides all <p> elements.
– $(".test").hide() //hides all elements with class="test".
– $("#test").hide() //hides the element with id="test"
Check weather the document loaded
• Execute the statements when the document is
completely loaded
$(document).ready(function( ){ set-statements });
• Why its necessary?
• Here are some examples of actions that can fail if
methods are run before the document is fully
loaded:
– Trying to hide an element that is not created yet
– Trying to get the size of an image that is not loaded yet
• Shortened notation for the syntax can be
$(function( ){ set-statements });
Selectors in JQuery
• $("*") Selects all the elements of HTML
• $("p") Selects all the p tags
• $("p:first") Selects only first p tag
• $(".class") Selects all the elements of css style class
• $("p.intro") Selects all p elements with css intro class
• $("ul li:first") Selects first li tag of first ul tag
• $("ul li:first-child") Selects first li tag of all ul tags
• $("[href]") Selects all elements having attribute href
• $("a[target='_blank']") Selects a tag with attribute and value
• $("a[target!='_blank']")  a tag with attribute and different value
• $(":button")  button tag and also input tag of button type
• $("tr:even") Selects Even tr tags
• $("tr:odd") Selects Odd tr tags
• $("#id") Selects an element with an id
JQuery events
click keypress submit load
dblclick keydown change resize
mouseenter keyup focus scroll
mouseleave blur unload
mouseup on
mousedown
hover
Events example
• Syntax $("p").click();
• Example : $("p").click(function(){alert();});

• To access the current element use this


keyword
• Example
– $("p").click(function(){
$(this).hide();
});
<html>
<head>
<title>Example program of JQuery event handler</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></
script>
</head>

<body>
<p id=“csbs”>CSBS Dept of ISE</p>

<script type=“text/javascript”>
$(document).ready(function( ){
$(“#csbs").click(function(){
$(this).hide();
});
});
</script>
</body>
</html>
<html>
<head>
<title>Example of JavaScript event handler</title>
</head>

<body>
<p id=“csbs”>CSBS Dept of ISE</p>

<script type=“text/javascript”>
document.getElementById(“csbs”).onclick = function () {
document.getElementById(“csbs”).style.display = “none”;
};
</script>
</body>
</html>
JQuery Effects
• show() element will be visible
• hide() element will be hidden
• toggle() element will toggle between hide or show
• fadeIn() slowly the element will appear on screen
• fadeOut() slowly the element will disappear
• fadeToggle() toggle between appear and disappear
• fadeTo(“ms”, “%”) opacity will be added based on input
• slideUp() animation of sliding up to hide
• slideDown() animation of sliding down to visible
• slideToggle() toggle between slideUp and slideDown
JQuery DOM Manipulation
• text()  sets or return the exiting value of element
• html()  sets or return the existing value with markup
• val()  sets or return the value of form elements
• attr()  adds or get the value of attribute of element
• append()  add content at the end of selected element
• prepend() add content at the starting of selected element
• after()  add content after the of selected element
• before()  add content before the of selected element
• remove()  remove all the children and the element
• empty()  removes only children but not the element
CSS manipulation
• addClass()
– Adds one or more classes to the selected elements
– $(“p”).addClass(“bg-dark”);

• removeClass()
– Removes one or more classes from the selected elements
– $(“p”).removeClass(“bg-dark”);

• toggleClass()
– Toggles between adding/removing classes from the selected elements
– $(“p”).toggleClass(“bg-dark”);

• css()
– Sets or returns the style attribute
– $(“p”).css(“background-color”, “blue”);
– $("p").css({"background-color": "yellow", "font-size": "200%"});
Height and width respect to Box model
• width()
• height()

• innerWidth()
• innerHeight()

• outerWidth()
• outerHeight()

• outerWidth(true)
• outerHeight(true)
Traversing
• Finding an other element by using the relation
of other element with current element in the
DOM Tree.
• If the current element is UL
• Parent id DIV
• Child is LI
• parent()
Traversing Ancestors
– Used to find the parent of current element
– Syntax: $(“ul").parent();
– Example:
• $(“ul").parent().addClass(“pb-5”);

• parents()
– Used to find all the parents of current element until html
– Syntax: $(“ul").parents();
– Example:
• $(“ul").parents().addClass(“pb-5”);

• parentsUntil()
– Used to find all the parents of current element until specified parent
– Syntax: $(“ul").parentsUntil(“parent name”);
– Example:
• $(“div").parentsUntil(“div”).css({"border": "2px solid red"});
Traversing  Descendants
• children()
– Used to select the children of the current element
– Syntax: $(“ul").children();
– Example:
• $(“ul").children().addClass(“mb-5”);
• $("div").children("p.first") .addClass(“mb-5”);

• find()
– Used to find selected element on any level of the DOM Tree
– If * is passed to find the child then all children will be selected
– Syntax: $(“ul").find(“span”);
– Example:
• $(“ul").find(“span”).addClass(“mb-5”);
• $(“ul").find(“*”). .addClass(“mt-5”);
Traversing  Siblings
• siblings()
– Used to select all sibling elements of the selected element
– Also can select the siblings of particular element by selectors
– Syntax: $(“selector").siblings();
– Example:
• $(“div").siblings().hide();
• $(“div").siblings(“div”).hide();

• next()
– Used to select the next sibling of current element.
– Syntax: $(“div").next();
– Example: $(“div").next().hide();

• nextAll()
– Used to select the next sibling of current element.
– Syntax: $(“div").nextAll();
– Example: $(“div").nextAll().hide();
Traversing  Siblings
• nextUntil()
– Used to select the next siblings of current element until the specified sibling.
– Syntax: $(“div").nextUntil(“h1”);
– Example: $(“div").nextUntil(“h1”).hide();

• prev()
– Used to select the previous sibling of current element.
– Syntax: $(“div").prev();
– Example: $(“div").prev().hide();

• prevAll()
– Used to select the previous siblings of current element.
– Syntax: $(“div").prevAll();
– Example: $(“div").prevAll().hide();

• prevUntil()
– Used to select the previous siblings of current element until the specified sibling.
– Syntax: $(“div").prevUntil(“h1”);
– Example: $(“div").prevUntil(“h1”).hide();
Traversing  filtering
• first()
– Used to select the first element of the specified elements
– Syntax: $(“div").first(“h1”);
– Example: $(“div").first(“h1”).css(“color”,“red”);

• last()
– Used to select the last element of the specified elements
– Syntax: $(“div").last(“h1”);
– Example: $(“div").last(“h1”).hide();

• eq()
– Used to select the element based on the index and index starts with 0
– Syntax: $(“div").eq(1);
– Example: $(“div").eq(0).hide();

• filter()
– Used to filter the elements and selects list of elements

• not()
– Works opposite to the filter()
AJAX
• AJAX is the art of exchanging data with a server, and updating
parts of a web page - without reloading the whole page.
• AJAX = Asynchronous JavaScript and XML
• Examples of applications using AJAX: Gmail, Google Maps,
Youtube, and Facebook tabs.
• With the jQuery AJAX methods, you can request text, HTML,
XML, or JSON from a remote server
• AJAX applications are much more faster and responsive as
compared to traditional web applications.
• On 18 February 2005 for the first time, Jesse James Garrett
introduce AJAX
• on 5th April 2006, the W3C(world wide web consortium) release
the first draft which contains the specifications for the
XMLHttpRequest object. After that AJAX will be popular
among web developers.
Steps how AJAX works
• A client event occurs.
• An XMLHttpRequest object is created.
• The XMLHttpRequest object is configured.
• The XMLHttpRequest object makes an asynchronous
request to the Webserver.
• The Webserver returns the result containing XML
document.
• The XMLHttpRequest object calls the callback()
function and processes the result.
• The HTML DOM is updated.
Advantages of AJAX
• It creates responsive and interactive web
applications.
• It supports the development of patterns and
frameworks that decrease the development time.
• It makes the best use of existing technology and
feature instead of using some new technology.
• It makes an asynchronous call to the web server
which means the client doesn't have to wait for
the data to arrive before starting rendering
AJAX
• AJAX applications initiate XMLHttpRequest to manage data requests
sent to the web servers and handle or monitor the data sent by the web
servers in a very effective manner. AJAX support the following types of
requests
– GET
• To retrieve data from a server
• The data is sent as a part of the URL that is appended at the end of the request
– POST
• To send data from a web page to a web server.
• The data is sent in the request body that is separated from the URL
– DELETE
• To delete data from the web server
• The data to be deleted is sent in the request body and the web server will delete that
data from its storage
– PUT
• To send data from a web page to a web server to update the existing content in the
server.
• The data is sent in the request body that is separated from the URL
AJAX
• To create a connection and send a request to the
web server AJAX supports the methods
– open()  to create the connection
– send()  to send the created connection
– open()
• Syntax: open(request method , url , async, user, password)
• Example:
Var csbsrequest = new XMLHttpRequest();
csbsrequest.open(“GET”,“https://jssstu.in/csbs.html”,true)
– send()
• csbsrequest.send()
AJAX Methods
• $.ajax(url, type, data, success, error);
• $.get(url, response);
• $.post(url, data, response);
• $.getJSON(url, response);
• $.getScript(url);
• $.load(url);
AJAX Method
• load(“url parameter”);
• load(“url parameter”, function(responseTxt, statusTxt, xhr))

– responseTxt actual output/ return value of function


– statusTxt  status of request indicating 5 states
• Information 101
• Success 202
• Redirection 303
• Client error 404
• Server error 505
– xhr  an xml Object to proved the information about status
• xhr.status
• xhr.statusText
Success Status Codes
200 OK If the request is OK.
When the request is complete and a
201 Created
new resource is created.
When the request is accepted by the
202 Accepted
server.
When there is no data in the response
204 No Content
body.
For additional inputs the browser
205 Reset Content
clears the form used for transaction.
Partial When the server returns the partial
206
Content data of the specified size.
Redirection status code
It is used to represent a link list. So
that user can select any one link and
300 Multiple Choices
go to that location. It allows only
five locations.

When the requested page is moved


301 Moved Permanently
to the new URL.

When the requested page is found in


302 Found
a different URL.

304 Not modified URL is not modified.


Client error status code
The server cannot fulfil the request because the request was
400 Bad Request
malformed or has invalid syntax.
The request needs authentication and the user does not
401 Unauthorised
provide valid credentials.
403 Forbidden The server understood the request but does not fulfil it.
404 Not Found The requested page is not found.
The method through which the request is made is not
405 Method Not Allowed
supported by the page.
The response generated by the server cannot be accepted by
406 Not Acceptable
the client.
408 Request Timeout Server timeout
409 Conflict The request does not fulfil due to a conflict in the request.
410 Gone The requested page is not available.
The server does not match the requirement of the Expect
417 Exception Failed
request header field.
Server error status code
When the server encounter error while processing the
500 Internal Server Error
request
When the server does not recognise the request method
501 Not Implemented
or lacks of ability to fulfil the request

When the server acts like a gateway and recovers an


502 Bad Gateway
invalid response from another server(upstream)

503 Service Unavailable When the server is not available or down

When the server acts like a gateway and does not receive
504 Gateway Timeout
a response from the other server(upstream) on time.

HTTP Version Not When the server does not support the version of the
505
Supported HTTP protocol.
Network Authentication When the client needs to authenticate to gain access to
511
Required the network.
Disadvantages of AJAX
• AJAX is fully dependent on Javascript. So if
JavaScript is disabled in your web browser
then you are not able to run the AJAX
webpage
• The debugging of AJAX applications is
difficult.
• If one request can fail then it may fail the load
of the complete webpage.
Get and Post method vs AJAX
• Get
– requests data from the server with an HTTP GET
request
– Syntax
• $.get(URL,callback);
– Example
• $.get("data.txt", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
Get and Post method vs AJAX
• Post
– requests data from the server with submission of
data to be processed with an HTTP POST request
– Syntax
• $.post(URL,{data_to : “process”},callback);
– Example
• $.post("data.txt",{ name: “A”}, function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
Get vs Post
• GET requests can be cached
• GET requests remain in the browser history
• GET requests can be bookmarked
• GET requests should never be used when dealing with sensitive data
• GET requests have length restrictions
• GET requests are only used to request data (not modify)

• POST requests are never cached


• POST requests do not remain in the browser history
• POST requests cannot be bookmarked
• POST requests have no restrictions on data length
Actions of Get vs Post
• On go-back / reload
– Get will not do any changes
– Data will be re-submitted
• data length
– Get methods adds the parameter with url max of 2048 characters
– No limit in data in post
• Data type
– In Get method Only ASCII characters are allowed
– Any characters even the binary also allowed
• Security
– Get method is less secured
– Post method is more secured
• Data Visibility
– Data is visible in the URL
– Data is hidden in post method.
Introduction to bootstrap
• Bootstrap 5 (released 2021) is the newest version
of Bootstrap with new components, faster stylesheet
and more responsiveness.
• Bootstrap is a free front-end framework for faster
and easier web development
• Bootstrap includes HTML and CSS based design
templates for typography, forms, buttons, tables,
navigation, modals, image and many other, as well
as optional JavaScript plugins
• Bootstrap also gives you the ability to easily create
responsive designs
Advantages of Bootstrap
• Easy to use: Anybody with just basic knowledge of HTML
and CSS can start using Bootstrap
• Responsive features: Bootstrap's responsive CSS adjusts to
phones, tablets, and desktops
• Mobile-first approach: In Bootstrap, mobile-first styles are
part of the core framework
• Browser compatibility: Bootstrap 5 is compatible with all
modern browsers (Chrome, Firefox, Edge, Safari, and Opera).
• Many users already have downloaded Bootstrap 5 from
jsDelivr when visiting another site. As a result, it will be
loaded from cache when they visit your site, which leads to
faster loading time.
how to get Bootstrap
• There are two ways to get bootstrap in to website
– Include Bootstrap 5 from a CDN (Content Delivery Network)
– Download Bootstrap 5 from getbootstrap.com

• <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/
dist/css/bootstrap.min.css" rel="stylesheet">

• <script src="https://cdn.jsdelivr.net/npm/
bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
Syntax of bootstrap
• Open tag of element
• class as an attribute
• The style needs to be applied should be the
value
• Ex:
<p class=“border”> CSBS </p>
Example of Bootstrap style
<div class="container">
<h1>CSBS First Bootstrap Page</h1>
<p>Information Science and Engineering .</p>
</div>
Extra Small Medium Large Extra XXL
small ≥576px ≥768px ≥992px Large ≥1400px
<576px ≥1200px
max- 100% 540px 720px 960px 1140px 1320px
width
Example of Bootstrap style
• <div class="container pt-5"></div>
– Gives padding top 5

• <div class="border"></div>
– Adds default border to element

• <div class=“bg-dark"></div>
– Adds dark background color
Variations in container
Class Extra small Small Medium Large Extra large XXL
<576px ≥576px ≥768px ≥992px ≥1200px ≥1400px

.container- 100% 540px 720px 960px 1140px 1320px


sm

.container- 100% 100% 720px 960px 1140px 1320px


md

.container- 100% 100% 100% 960px 1140px 1320px


lg

.container- 100% 100% 100% 100% 1140px 1320px


xl

.container- 100% 100% 100% 100% 100% 1320px


xxl
Grids
• To construct a grids we use 2 classes
– row
• Represents a row of the grids
– col
• Represents a column of the grids
• col-sm
• col-md
• col-lg
• col-xl
• col-xxl
Grids Example
<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-3"></div>
<div class="col-sm-3"></div>
</div>
Typography / text formatting
• h1, h2, h3, h4, h5, h6 can be used as class
• display-1, display-2, display-3, display-4,
display-5, display-6 can be used for class
name to have even larger text
• small, mark,
• text-start, text-break, text-center, text-end,
text-lowercase, text-uppercase, text-capitalize
• text-decoration-none
Text-colors of bootstrap
• This text is muted.
• This text is important or primary.
• This text indicates success.
• This text represents some information.
• This text represents a warning.
• This text represents danger.
• Secondary text.
• Dark grey text.
• Body text.
• Light grey text.
Background colors
• bg-primary
• bg-success
• bg-info
• bg-warning
• bg-danger
• bg-secondary
• bg-dark
• bg-light
Table colors
• “table-primary”
• “table-success”
Images
• rounded
• rounded-circle
• img-thumbnail
• float-start
• float-end
• mx-auto d-block
• img-fluid
button
• btn
• btn-primary
• btn-success
• btn-secondary btn-lg
• btn-info btn-small
• btn-warning d-grid
• btn-danger badge
• btn-dark
• btn-light
• btn-link
Spinners
<div class="spinner-border"></div>
<div class="spinner-grow text-info"></div>
Color spinners
<div class="spinner-border text-muted"></div>
<div class="spinner-border text-primary"></div>
<div class="spinner-border text-success"></div>
<div class="spinner-border text-info"></div>
<div class="spinner-border text-warning"></div>
<div class="spinner-border text-danger"></div>
<div class="spinner-border text-secondary"></div>
<div class="spinner-border text-dark"></div>
<div class="spinner-border text-light"></div>
Themes
• Bootstrap support 2 themes
– Light
– Dark
• By default bootstrap background will be white or light
theme
• If we need to change to dark theme
data-bs-theme="dark“
Use this as an attribute for the html or on to particular element
needed to apply.

<table class="table" data-bs-theme="dark">


Try by yourself
• Create a form to represent the usage of various
bootstrap colors and buttons.
• Create a button using a tag
• Illustrate the usage of loading spinners and
growing spinners
• Create a basic grid structure with 3 column
and align to the center.
Introduction React JS
• React JS was developed by Jordan Walke in 2010 from a
team of Facebook. Released in July 2013.
• The library is used to building user interface, particularly
single page websites where it need fast, interactive experience.
• Current version of React JS is v18.0.0 released on april 2022
• React creates a VIRTUAL DOM in memory.
• To use React JS in production Node JS is necessary
• It is a simple, feature rich and component based UI library
• React develops applications by creating various reusable and
independent codes. This UI library is, thus, widely used in web
development.
Why ReactJS
• Component Based  reuse
• Better and Faster Performance virtual DOM
• Extremely Flexible
• Creates dynamic applications easily
• Develops Mobile Applications as well
• Debugging is Easy  unidirectional
Installation
• Prerequisite
– React CLI tools depends on the Node.js and must be
installed in your system.
– Verify node.js installed or not using node –version
– https://nodejs.org/en/download/
• Install Serve or any program to render the code on to
web screen.
– npm install serve -g
– By default serve will render in localhost:5000 if the port is
busy it will pick different port and displays on the terminal
• npm install -g create-react-app
• npm install react-scripts@latest
How to start with React
• npx create-react-app react-app-name
– Used to set up the environment for react js
• Get into the directory created by using cd
– cd react-app-name
• npm start
– This will start a local host serving on the port 3000
– localhost:3000
Structure of ReactJS
|-- README.md
|-- node_modules
|-- package-lock.json
|-- package.json
|-- public
| |-- favicon.ico
| |-- index.html
| |-- manifest.json
| `-- robots.txt
`-- src
|-- App.css
|-- App.js
|-- App.test.js
|-- index.css
|-- index.js
|-- logo.svg
|-- reportWebVitals.js
`-- setupTests.js
Important files of ReactJS
• index.js
– Entry point of the application. It
uses ReactDOM.render method to kick-start and start the
application.
• index.css
– Used to styles of the entire application. Let us remove all
styles and start with fresh code.
• App.js
– Root component of our application. Let us replace the
existing JSX and show simple hello react message as
shown below
JSX
• JSX  JavaScript + XML
• This allows to write HTML like code in
JavaScript
– const element = <h1>Hello, world</h1>;
• To display the JavaScript variables or value in
JSX { } are useful they are also called as
handlebars
– const title = “CSBS”;
– const element = <h1>it’s a { title } class</h1>;
Import ReactJS library to the project
import React from 'react';
import ReactDOM from 'react-dom/client';

const container = document.getElementById('root');

const root = ReactDOM.createRoot(container);


root.render(<p>Hello World</p>);

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<p>Hello World</p>);
ReactJS with CDN
• ReactJS also has two versions of CDN
– Development
• <script crossorigin
src="https://unpkg.com/react@18/umd/react.development.js"></scri
pt>
• <script crossorigin
src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js"></script>
– Production
• <script crossorigin
src="https://unpkg.com/react@18/umd/react.production.min.js"></s
cript>
• <script crossorigin
src="https://unpkg.com/react-dom@18/umd/react-
dom.production.min.js"></script>
Example
<html>
<body>
<div id="react-app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"
crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-
dom.development.js" crossorigin></script>

<script language="JavaScript">
element = React.createElement('h1', {}, 'Hello React!')
ReactDOM.render(element, document.getElementById('react-app'));
</script>

</body>
</html>
Advantages of ReactJS
• Performance
• Easy to learn
• Huge collection of third party components
• Large community
• SEO Friendliness
• Easy kick-starting of the React project
• Rich set of developer tools
• Handle large application
Class
- React development is based on components
- Components are self-contained, reusable units
of UI and logic
- React projects typically contain many
components
- While React components can be a function or
a class
Class
• React Class Components are JavaScript
classes that extend React.Component
• They define the UI, and handle events within
the application
• The render() method in react class components
returns JSX elements describing the UI of the
Application.
Example of default class
// Filename App.js

import React from "react";

class App extends React.Component {


render() {
return <h1> CSBS </h1>;
}
}

export default App;


Example class
import React from 'react';
import ReactDOM from 'react-dom/client';

class Car extends React.Component {


render() {
return <h2>Hi, I am a Car!</h2>;
}
}

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


root.render(<Car />);
Reusing of one component in other
// Filename - App.js
import React from "react";

class Sample extends React.Component {


render() {
return <h1> Computer Science and </h1>;
}
}

class App extends React.Component {


render() {
return <Sample /> <h1>Business Systems</h1>;
}
}

export default App;


Forms
• React Forms are the components used to
collect and manage the user inputs. These
components includes the input elements like
– text field,
– check box,
– date input,
– dropdowns
etc.
Forms
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyForm />);
Forms
• This will work as normal, the form will submit and the
page will refresh.
• But this is generally not what we want to happen in
React.
• We want to prevent this default behavior and let React
control the form

• So to manage the inputs in react we have useState


hook
• And an onChange handler
Forms Example
import { useState } from 'react';
import ReactDOM from 'react-dom/client';

function MyForm() { const [name, setName] = useState("");

return (
<form>
<label>Enter your name:
<input type="text" value={name}
onChange={(e) => setName(e.target.value)} />
</label>
</form>
)
}

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


root.render(<MyForm />);
Events
• Similar to the DOM events, React can perform
actions based on user events.
• HTML JavaScript event
– <button onclick=“myfun()">Click here</button>

• React JavaScript event


– <button onClick={myfun}>Click here</button>
Example of event

function CSBS() {
const myaction = () => { alert(“Button Clicked!"); }
return (<button onClick={myaction}>Click here!</button>);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<CSBS />);
Event handlers
• onClick
• onDrag
• onDoubleClick

• onKeyDown
• onKeyPress
• onKeyUp
• onChange

• onFocus
• onBlur
• onSubmit
Conditionals
) ;
1>
function Goal(props) { { </h
l ( ) ss
const isGoal = props.isGoal; oa c ce > );
eG >Su ) { /h1
if (isGoal) { a d 1 a l( re<
M (< h o ilu
return <MadeGoal/>; i on n d G a
c t u r sse > F
un r e t i 1
} f M (< h
n
io urn
return <MissedGoal/>; c t t
fu n re
}
}

}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />)
Lists
import React from 'react';
in ReactJS
import ReactDOM from 'react-dom/client';

function CarName(props) { return <li>Car Name: { props.brand }</li>; }

function Garage( ) {
const cars = ['Ford', 'BMW', 'Audi'];
return ( <div>
<h1>Cars in my garage?</h1>
<ul>
{cars.map((car) => <CarName brand={car} />)}
</ul>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));

You might also like