SlideShare a Scribd company logo
React Components
1
React Components
Components are like functions that return HTML
elements.
React Components
Components are independent and reusable bits of
code. They serve the same purpose as JavaScript
functions, but work in isolation and return HTML.
Components come in two types, Class components
and Function components.
2
Create Your First Component
When creating a React component, the component's
name MUST start with an upper case letter.
Class Component
A class component must include the extends
React.Component statement. This statement creates
an inheritance to React.Component, and gives your
component access to React.Component's functions.
The component also requires a render() method, this
method returns HTML.
3
Example
Create a Class component called Car
4
Example
Function Component
Here is the same example as previous, but created
using a Function component instead.
A Function component also returns HTML, and
behaves much the same way as a Class component,
but Function components can be written using much
less code, are easier to understand.
5
Example
Function Component
Example
Create a Function component called Car
6
Rendering a Component
Now your React application has a component called
Car, which returns an <h2> element.
To use this component in your application, use similar
syntax as normal HTML: <Car />
To display the Car component in the "root" element:
7
Rendering a Component
8
Props
9
Components can be passed as props, which stands
for properties.
Props are like function arguments, and you send them
into the component as attributes.
Example
Use an attribute to pass a color to the Car component,
and use it in the render() function:
Props: Example
10
Components in Components
11
We can refer to components inside other components:
Components in Components
12
React JSX
1
What is JSX
JSX stands for JavaScript XML.
JSX allows us to write HTML in React.
JSX makes it easier to write and add HTML in React.
2
Coding JSX
JSX allows us to write HTML elements in JavaScript
and place them in the DOM without any
createElement() and/or appendChild() methods.
JSX converts HTML tags into react elements.
You are not required to use JSX, but JSX makes it
easier to write React applications.
3
Coding JSX: Example 1 (WITH JSX)
4
OUTPUT
Coding JSX: Example 1 (WITHOUT JSX)
5
OUTPUT
As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.
Expressions in JSX
With JSX you can write expressions inside curly
braces { }.
The expression can be a React variable, or
property, or any other valid JavaScript expression.
JSX will execute the expression and return the
result:
6
Expressions in JSX: Example
Execute the expression 5 + 5:
7
OUTPUT
Inserting a Large Block of HTML
8
To write HTML on multiple lines, put the HTML inside
parentheses:
Create a list with three list items:
Inserting a Large Block of HTML
9
One Top Level Element
10
The HTML code must be wrapped in ONE top level
element.
So if you like to write two paragraphs, you must put
them inside a parent element, like a div element.
Wrap two paragraphs inside one DIV element:
One Top Level Element
11
• JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.
One Top Level Element
12
• Alternatively, you can use a "fragment" to wrap multiple lines.
This will prevent unnecessarily adding extra nodes to the DOM.
• A fragment looks like an empty HTML tag: <></>.
• Wrap two paragraphs inside a fragment:
One Top Level Element
13
One Top Level Element
14
JSX follows XML rules, and therefore HTML elements
must be properly closed.
Close empty elements with />
JSX will throw an error if the HTML is not properly closed.
Attribute class = className
15
The class attribute is a much used attribute in HTML, but
since JSX is rendered as JavaScript, and the class
keyword is a reserved word in JavaScript, you are not
allowed to use it in JSX.
Use attribute className instead.
JSX solved this by using className instead. When JSX is
rendered, it translates className attributes into class
attributes.
Example
Use attribute className instead of class in JSX:
Attribute class = className
16
Conditions - if statements
17
React supports if statements, but not inside JSX.
To be able to use conditional statements in JSX, you
should put the if statements outside of the JSX, or
you could use a ternary expression instead:
Option 1:
Write if statements outside of
the JSX code:
Write "Hello" if x is less than 10,
otherwise "Goodbye":
Conditions - if statements
18
Conditions - if statements
19
Option 2:
Use ternary expressions instead:
Example
Write "Hello" if x is less than 10, otherwise
"Goodbye":
Note that in order to embed a JavaScript expression inside JSX, the JavaScript must be
wrapped with curly braces, {}.
React JS
Components
State and Props
Lifecycle of Components
Rendering List and Portals
Error Handling
Routers
Components: The Building Blocks of React
Applications
• In React, components are the fundamental units that structure your
user interface (UI). They encapsulate a specific portion of your UI,
including its visual representation (JSX) and logic (JavaScript
functions). This modular approach offers several advantages:
• Reusability
• Isolation
• Composability
Components: The Building Blocks of React
Applications
• Reusability: You can create a component once and use it multiple
times throughout your application, promoting code maintainability
and efficiency.
• Isolation: Components act as independent units, making your code
easier to understand, test, and maintain. Changes within a
component are less likely to have unintended consequences
elsewhere in your app.
• Composability: Components can be nested within each other,
allowing you to build complex UIs from simpler ones. This hierarchical
structure promotes organization and scalability.
Types of Components in React
• There are two primary ways to define components in React:
1. Functional Components (Recommended):
• Defined using JavaScript functions that return JSX.
• Simpler and more concise for most UI elements.
• Leverage hooks (introduced in React 16.8) to manage state and side
effects within functional components.
Types of Components in React
1. Class-Based Components (Legacy):
• Defined using JavaScript classes that extend React.Component.
• More complex syntax, often used for components with complex state
management or lifecycle methods.
Using Components in Your Application
• You can render components directly within your main App.js or
other components using JSX syntax:
Using Components in Your Application
• Components can receive data (props) to customize their behavior:
Key Concepts Related to Components
• Props: Act like function arguments, allowing you to pass data
from parent to child components.
• State: Internal data managed within a component, allowing it to
respond to user interactions and update its UI. State is usually
managed using hooks in functional components or the this.state
object in class components.
• JSX: A syntax extension that allows you to write HTML-like
structures within JavaScript code.
State and Props: The Cornerstones of React
Component Data
• In React, state and props are essential concepts for managing
and passing data within your components. They determine
how components display information and respond to user
interactions.
1. State
2. Props
State and Props: The Cornerstones of React
Component Data
1. State:
• Internal data managed by a component.
• Represents the component's dynamic state that can change
over time.
• Used to control the UI's appearance and behavior based on
user actions or external events.
• Managed using hooks (useState) in functional components
or the this.state object in class components.
Example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state with initial count (0)
function handleClick() {
setCount(count + 1); // Update state using the setter function
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
Props
• Data passed down from parent components to child
components.
• Provide external configuration options to child components.
• Immutable (cannot be modified directly by the child
component).
• Used for static data or data that shouldn't be changed by the
child component.
Key Differences between State and Props
When to Use State vs. Props
• Use state when you need data to change within a component
based on user interactions or external events.
• Use props when you need to pass data down from a parent
component to configure a child component's behavior or
appearance.
By effectively utilizing state and props, you can create dynamic and
interactive React applications where components can manage
their internal data and receive external configuration.
React Lifecycle
Lifecycle of Components
• Each component in React has a lifecycle which you can monitor and
manipulate during its three main phases.
• The three phases are:
• Mounting,
• Updating, and
• Unmounting.
React Lifecycle
React Lifecycle
Mounting
• Mounting means putting elements into the DOM.
• React has four built-in methods that gets called, in this order, when
mounting a component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()
The render() method is required and will always be called, the others
are optional and will be called if you define them.
React Lifecycle
Mounting
1. constructor
• The constructor() method is called before anything else, when the
component is initiated, and it is the natural place to set up the
initial state and other initial values.
2. getDerivedStateFromProps
• The getDerivedStateFromProps() method is called right before
rendering the element(s) in the DOM. This is the natural place to set
the state object based on the initial props.
• It takes state as an argument, and returns an object with changes to
the state
React Lifecycle
Mounting
3. Render
• The render() method is required, and is the method that actually
outputs the HTML to the DOM.
4. componentDidMount
• The componentDidMount() method is called after the component is
rendered.
• This is where you run statements that requires that the component
is already placed in the DOM.
React Lifecycle
Updating
• The next phase in the lifecycle is when a component is updated.
• A component is updated whenever there is a change in the
component's state or props.
• React has five built-in methods that gets called, in this order, when
a component is updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
The render() method is required and will always be called, the others
are optional and will be called if you define them.
React Lifecycle
Updating:
1. getDerivedStateFromProps
• Also at updates the getDerivedStateFromProps method is called.
This is the first method that is called when a component gets
updated.
• This is still the natural place to set the state object based on the
initial props.
2. shouldComponentUpdate
• In the shouldComponentUpdate() method you can return a
Boolean value that specifies whether React should continue with
the rendering or not.
• The default value is true.
React Lifecycle
Updating:
3. render
• The render() method is of course called when a component gets
updated, it has to re-render the HTML to the DOM, with the new
changes.
4. getSnapshotBeforeUpdate
• In the getSnapshotBeforeUpdate() method you have access to the
props and state before the update, meaning that even after the
update, you can check what the values were before the update.
• If the getSnapshotBeforeUpdate() method is present, you should
also include the componentDidUpdate() method, otherwise you
will get an error.
React Lifecycle
Updating:
5. componentDidUpdate
• The componentDidUpdate method is called after the component is
updated in the DOM.
React Lifecycle
Unmounting
• The next phase in the lifecycle is when a component is removed
from the DOM, or unmounting as React likes to call it.
• React has only one built-in method that gets called when a
component is unmounted:
• componentWillUnmount()
• The componentWillUnmount method is called when the component
is about to be removed from the DOM.
Rendering List: React Lists
• In React, you will render lists with some type of loop.
• The JavaScript map() array method is generally the preferred
method.
• Example:
• Let's render all of the cars from our garage:
Rendering List: React Lists
Rendering List: React Lists
• When you run this code in your create-react-app, it will work but
you will receive a warning that there is no "key" provided for the
list items.
Rendering List: React Lists
Keys
• Keys allow React to keep track of elements. This way, if an item is
updated or removed, only that item will be re-rendered instead of
the entire list.
• Keys need to be unique to each sibling. But they can be duplicated
globally.
• Generally, the key should be a unique ID assigned to each item.
Rendering List: React Lists
Keys
What are ReactJS Portals?
• Portals allow you to render components outside of the normal
component hierarchy
• The normal component hierarchy is a tree structure, where each
component is a child of another component
• Portals allow you to break out of this tree structure and render a
component anywhere in the DOM
• ReactJS components are typically rendered in a tree-like structure. Each
component is a child of another component, and the root of the tree is
the component that is mounted to the DOM. Portals allow you to break
out of this tree structure and render a component anywhere in the the
DOM.
Why Use Portals?
• There are a number of reasons why you might want to use portals in
your React application. Some common use cases include:
1. Modals
2. Tooltips
3. Dropdowns
4. Any component that needs to be positioned in a specific location in
the DOM
Why Use Portals?
• Modals: Modals are dialog boxes that appear on top of the rest of the
content on a page. Portals are a great way to create modals because
they allow you to render the modal content outside of the normal
component hierarchy. This means that the modal content won't be
affected by the styles or layout of the rest of the page.
• Tooltips: Tooltips are small pieces of text that appear when you hover
over an element. Portals can be used to render tooltips outside of the
normal component hierarchy. This means that the tooltip content won't
be affected by the styles or layout of the element that it is associated
with.
Why Use Portals?
• Dropdowns: Dropdowns are menus that appear when you click on a
button. Portals can be used to render dropdowns outside of the normal
component hierarchy. This means that the dropdown content won't be
affected by the styles or layout of the button that it is associated with.
How to Use Portals
• The createPortal function
• The first argument to createPortal is the child component that you
want to render
• The second argument to createPortal is the DOM element that you
want to render the child component into.
• Portals are created using the createPortal function. The first argument
to createPortal is the child component that you want to render. The
second argument to createPortal is the DOM element that you want to
render the child component into.
• Here is an example of how to use the createPortal function:
How to Use Portals
• JavaScript
• import React from 'react';
• import ReactDOM from 'react-dom';
• const modalRoot = document.getElementById('modal-root');
• function Modal() {
• return (
• <div>
• <h1>This is a modal</h1>
• <button onClick={() => onClose()}>Close</button>
• </div>
• );
• }
• function App() {
• const [showModal, setShowModal] = useState(false);
• const openModal = () => setShowModal(true);
• const onClose = () => setShowModal(false);
• return (
• <div>
• <button onClick={openModal}>Open Modal</button>
• {showModal && ReactDOM.createPortal(<Modal onClose={onClose} />, modalRoot)}
• </div>
• );
• }
• ReactDOM.render(<App />, document.getElementById('root'));
Bootstrap
UNIT 3
ADV. WEB TECH.
Introduction to Bootstrap
• Bootstrap is a free and popular HTML, CSS, and
JavaScript framework. The following are the features of
Bootstrap:
• Faster and easier web development
• Responsive Website (Web sites that automatically adjust
themselves on all devices)
• Modern Web Browsers
• Mobile-first approach
Introduction to Bootstrap
• Bootstrap is a free and open-source front-end framework for
designing and developing responsive, mobile-first websites.
• It consists of pre-designed components like buttons, forms,
navigation bars, and more, built with HTML, CSS, and
JavaScript.
• These components can be easily customized and used to
create websites that look great and work well on all devices,
from desktops to smartphones.
Introduction to Bootstrap
• Think of Bootstrap as a toolbox for web developers.
• It provides a set of ready-made tools that you can use to build your
website quickly and easily, without having to code everything from
scratch.
• This saves you time and effort, and it also helps to ensure that your
website is consistent and well-designed.
Features of Bootstrap:
• Responsive design: Bootstrap is designed to be mobile-first, which
means that your website will look great on all devices, regardless of
their screen size. This is important in today's world, where more and
more people are using their smartphones and tablets to browse the
web.
• Easy to use: Bootstrap is very easy to learn, even for beginners. The
documentation is clear and concise, and there are plenty of tutorials
and examples available online.
• Customizable: Bootstrap is highly customizable. You can change the
colors, fonts, and styles of the components to match your brand or
website design.
• Open source: Bootstrap is open source, which means that it is free to
use and modify. This makes it a great choice for both personal and
commercial projects.
Bootstrap Setup
• There are two ways to start using Bootstrap 5 on your own web site.
1. Include Bootstrap 5 from a CDN
2. Download Bootstrap 5 from getbootstrap.com
Bootstrap Setup
1. Bootstrap 5 CDN
• If you don't want to download and host Bootstrap 5 yourself, you can
include it from a CDN (Content Delivery Network).
• jsDelivr provides CDN support for Bootstrap's CSS and JavaScript:
Bootstrap Setup
2. Downloading Bootstrap 5
If you want to download and host Bootstrap 5 yourself, go to
https://getbootstrap.com/, and follow the instructions there.
Bootstrap Containers
• Bootstrap 5 also requires a containing element to wrap site contents.
• Containers are used to pad the content inside of them, and there are
two container classes available:
1. The .container class provides a responsive fixed width container
2. The .container-fluid class provides a full width container, spanning
the entire width of the viewport
Bootstrap Containers
Bootstrap Grids
The grid system is responsive, and the columns will re-arrange automatically depending on the
screen size.
Bootstrap Grids
Bootstrap Grids Basic Structure of a Bootstrap 5 Grid
• First example: create a row (<div class="row">). Then, add the desired
number of columns (tags with appropriate .col-*-* classes). The first star (*)
represents the responsiveness: sm, md, lg, xl or xxl, while the second star
represents a number, which should add up to 12 for each row.
• Second example: instead of adding a number to each col, let bootstrap
handle the layout, to create equal width columns: two "col" elements =
50% width to each col, while three cols = 33.33% width to each col. Four
cols = 25% width, etc. You can also use .col-sm|md|lg|xl|xxl to make the
columns responsive.
Bootstrap Grids
Bootstrap Tables
A basic Bootstrap 5 table has a light padding and horizontal dividers.
• The .table class adds basic styling to a table:
Bootstrap Tables
Striped Rows
• The .table-striped class adds zebra-stripes to a table:
Bootstrap Tables
Bordered Table
• The .table-bordered class adds borders on all sides of the table and
cells:
Bootstrap Tables
Hover Rows
• The .table-hover class adds a hover effect (grey background color) on
table rows:
Bootstrap Tables
Black/Dark Table
• The .table-dark class adds a black background to the table:
Bootstrap Tables
Borderless Table
• The .table-borderless class removes borders from the table:
Bootstrap Buttons
• Bootstrap 5 provides different styles of buttons:
Bootstrap Buttons
• The button classes can be used on <a>, <button>, or <input>
elements:
Bootstrap Buttons
Button Outline
• Bootstrap 5 also provides eight outline/bordered buttons.
• Move the mouse over them to see an additional "hover" effect:
Bootstrap Buttons
Button Sizes
• Use the .btn-lg class for large buttons or .btn-sm class for
small buttons:
Bootstrap Buttons
Block Level Buttons
• To create a block level button that spans the entire width of the
parent element, use the .d-grid "helper" class on the parent
element:
Bootstrap Buttons
Spinner Buttons
• You can also add "spinners" to a button:
Navbars
• A navigation bar is a navigation header that is placed at the top of the
page.
Navbars
Navbars
Alerts
• Bootstrap provides an easy way to create predefined alert messages.
• Alerts are created with the .alert class, followed by one of the contextual classes .alert-success,
.alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light or .alert-
dark:
Alerts
Bootstrap Carousel
• The Carousel is a slideshow for cycling through elements:
Bootstrap Carousel
• The Carousel is a slideshow for cycling through elements:
Bootstrap Carousel
• The carousel is a slideshow for cycling through a series of content, built with CSS 3D
transforms and a bit of JavaScript. It works with a series of images, text, or custom
markup. It also includes support for previous/next controls and indicators.
Bootstrap Forms
Bootstrap Forms
Bootstrap Forms
Bootstrap Forms
Bootstrap Forms
Bootstrap Forms
Adding Colors
Adding Colors
Styling Text
Styling Text
Styling Text

More Related Content

PPTX
PPTX
What are the components in React?
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
PDF
react hook and wesite making structure ppt
PDF
REACTJS.pdf
PPTX
React-JS.pptx
PDF
React Best Practices All Developers Should Follow in 2024.pdf
PDF
React Interview Question PDF By ScholarHat
What are the components in React?
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
react hook and wesite making structure ppt
REACTJS.pdf
React-JS.pptx
React Best Practices All Developers Should Follow in 2024.pdf
React Interview Question PDF By ScholarHat

Similar to unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf (20)

PDF
Fundamental concepts of react js
PPTX
Introduction to React JS.pptx
PPTX
React JS Interview Question & Answer
PDF
100 React Interview questions 2024.pptx.pdf
PPTX
React js
PPTX
Introduction to ReactJS UI Web Dev .pptx
PPTX
Unit 2 Fundamentals of React -------.pptx
PDF
Copy of React_JS_Notes.pdf
PPTX
reactJS
PPTX
React JS - A quick introduction tutorial
PPTX
Dyanaimcs of business and economics unit 2
PPTX
ReactJS.pptx
PPTX
React Class Components vs Functional Components: Which is Better?
PPTX
React JS: A Secret Preview
PDF
Getting Started with React, When You’re an Angular Developer
PDF
React JS Interview Questions PDF By ScholarHat
PPTX
React - Start learning today
PPTX
Presentation1
PPTX
React Hooks Best Practices in 2022.pptx
PDF
Fundamental concepts of react js
Introduction to React JS.pptx
React JS Interview Question & Answer
100 React Interview questions 2024.pptx.pdf
React js
Introduction to ReactJS UI Web Dev .pptx
Unit 2 Fundamentals of React -------.pptx
Copy of React_JS_Notes.pdf
reactJS
React JS - A quick introduction tutorial
Dyanaimcs of business and economics unit 2
ReactJS.pptx
React Class Components vs Functional Components: Which is Better?
React JS: A Secret Preview
Getting Started with React, When You’re an Angular Developer
React JS Interview Questions PDF By ScholarHat
React - Start learning today
Presentation1
React Hooks Best Practices in 2022.pptx
Ad

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Business Ethics Teaching Materials for college
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Basic Mud Logging Guide for educational purpose
human mycosis Human fungal infections are called human mycosis..pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
O7-L3 Supply Chain Operations - ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Business Ethics Teaching Materials for college
GDM (1) (1).pptx small presentation for students
Week 4 Term 3 Study Techniques revisited.pptx
Cardiovascular Pharmacology for pharmacy students.pptx
PPH.pptx obstetrics and gynecology in nursing
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Open folder Downloads.pdf yes yes ges yes
The Final Stretch: How to Release a Game and Not Die in the Process.
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Open Quiz Monsoon Mind Game Prelims.pptx
Ad

unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf

  • 2. React Components Components are like functions that return HTML elements. React Components Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components. 2
  • 3. Create Your First Component When creating a React component, the component's name MUST start with an upper case letter. Class Component A class component must include the extends React.Component statement. This statement creates an inheritance to React.Component, and gives your component access to React.Component's functions. The component also requires a render() method, this method returns HTML. 3
  • 4. Example Create a Class component called Car 4
  • 5. Example Function Component Here is the same example as previous, but created using a Function component instead. A Function component also returns HTML, and behaves much the same way as a Class component, but Function components can be written using much less code, are easier to understand. 5
  • 6. Example Function Component Example Create a Function component called Car 6
  • 7. Rendering a Component Now your React application has a component called Car, which returns an <h2> element. To use this component in your application, use similar syntax as normal HTML: <Car /> To display the Car component in the "root" element: 7
  • 9. Props 9 Components can be passed as props, which stands for properties. Props are like function arguments, and you send them into the component as attributes. Example Use an attribute to pass a color to the Car component, and use it in the render() function:
  • 11. Components in Components 11 We can refer to components inside other components:
  • 14. What is JSX JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React. 2
  • 15. Coding JSX JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications. 3
  • 16. Coding JSX: Example 1 (WITH JSX) 4 OUTPUT
  • 17. Coding JSX: Example 1 (WITHOUT JSX) 5 OUTPUT As you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.
  • 18. Expressions in JSX With JSX you can write expressions inside curly braces { }. The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result: 6
  • 19. Expressions in JSX: Example Execute the expression 5 + 5: 7 OUTPUT
  • 20. Inserting a Large Block of HTML 8 To write HTML on multiple lines, put the HTML inside parentheses: Create a list with three list items:
  • 21. Inserting a Large Block of HTML 9
  • 22. One Top Level Element 10 The HTML code must be wrapped in ONE top level element. So if you like to write two paragraphs, you must put them inside a parent element, like a div element. Wrap two paragraphs inside one DIV element:
  • 23. One Top Level Element 11 • JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.
  • 24. One Top Level Element 12 • Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM. • A fragment looks like an empty HTML tag: <></>. • Wrap two paragraphs inside a fragment:
  • 25. One Top Level Element 13
  • 26. One Top Level Element 14 JSX follows XML rules, and therefore HTML elements must be properly closed. Close empty elements with /> JSX will throw an error if the HTML is not properly closed.
  • 27. Attribute class = className 15 The class attribute is a much used attribute in HTML, but since JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX. Use attribute className instead. JSX solved this by using className instead. When JSX is rendered, it translates className attributes into class attributes. Example Use attribute className instead of class in JSX:
  • 28. Attribute class = className 16
  • 29. Conditions - if statements 17 React supports if statements, but not inside JSX. To be able to use conditional statements in JSX, you should put the if statements outside of the JSX, or you could use a ternary expression instead: Option 1: Write if statements outside of the JSX code: Write "Hello" if x is less than 10, otherwise "Goodbye":
  • 30. Conditions - if statements 18
  • 31. Conditions - if statements 19 Option 2: Use ternary expressions instead: Example Write "Hello" if x is less than 10, otherwise "Goodbye": Note that in order to embed a JavaScript expression inside JSX, the JavaScript must be wrapped with curly braces, {}.
  • 32. React JS Components State and Props Lifecycle of Components Rendering List and Portals Error Handling Routers
  • 33. Components: The Building Blocks of React Applications • In React, components are the fundamental units that structure your user interface (UI). They encapsulate a specific portion of your UI, including its visual representation (JSX) and logic (JavaScript functions). This modular approach offers several advantages: • Reusability • Isolation • Composability
  • 34. Components: The Building Blocks of React Applications • Reusability: You can create a component once and use it multiple times throughout your application, promoting code maintainability and efficiency. • Isolation: Components act as independent units, making your code easier to understand, test, and maintain. Changes within a component are less likely to have unintended consequences elsewhere in your app. • Composability: Components can be nested within each other, allowing you to build complex UIs from simpler ones. This hierarchical structure promotes organization and scalability.
  • 35. Types of Components in React • There are two primary ways to define components in React: 1. Functional Components (Recommended): • Defined using JavaScript functions that return JSX. • Simpler and more concise for most UI elements. • Leverage hooks (introduced in React 16.8) to manage state and side effects within functional components.
  • 36. Types of Components in React 1. Class-Based Components (Legacy): • Defined using JavaScript classes that extend React.Component. • More complex syntax, often used for components with complex state management or lifecycle methods.
  • 37. Using Components in Your Application • You can render components directly within your main App.js or other components using JSX syntax:
  • 38. Using Components in Your Application • Components can receive data (props) to customize their behavior:
  • 39. Key Concepts Related to Components • Props: Act like function arguments, allowing you to pass data from parent to child components. • State: Internal data managed within a component, allowing it to respond to user interactions and update its UI. State is usually managed using hooks in functional components or the this.state object in class components. • JSX: A syntax extension that allows you to write HTML-like structures within JavaScript code.
  • 40. State and Props: The Cornerstones of React Component Data • In React, state and props are essential concepts for managing and passing data within your components. They determine how components display information and respond to user interactions. 1. State 2. Props
  • 41. State and Props: The Cornerstones of React Component Data 1. State: • Internal data managed by a component. • Represents the component's dynamic state that can change over time. • Used to control the UI's appearance and behavior based on user actions or external events. • Managed using hooks (useState) in functional components or the this.state object in class components.
  • 42. Example import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // Initialize state with initial count (0) function handleClick() { setCount(count + 1); // Update state using the setter function } return ( <div> <p>You clicked {count} times</p> <button onClick={handleClick}>Click me</button> </div> ); }
  • 43. Props • Data passed down from parent components to child components. • Provide external configuration options to child components. • Immutable (cannot be modified directly by the child component). • Used for static data or data that shouldn't be changed by the child component.
  • 44. Key Differences between State and Props
  • 45. When to Use State vs. Props • Use state when you need data to change within a component based on user interactions or external events. • Use props when you need to pass data down from a parent component to configure a child component's behavior or appearance. By effectively utilizing state and props, you can create dynamic and interactive React applications where components can manage their internal data and receive external configuration.
  • 46. React Lifecycle Lifecycle of Components • Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. • The three phases are: • Mounting, • Updating, and • Unmounting.
  • 48. React Lifecycle Mounting • Mounting means putting elements into the DOM. • React has four built-in methods that gets called, in this order, when mounting a component: 1. constructor() 2. getDerivedStateFromProps() 3. render() 4. componentDidMount() The render() method is required and will always be called, the others are optional and will be called if you define them.
  • 49. React Lifecycle Mounting 1. constructor • The constructor() method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values. 2. getDerivedStateFromProps • The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props. • It takes state as an argument, and returns an object with changes to the state
  • 50. React Lifecycle Mounting 3. Render • The render() method is required, and is the method that actually outputs the HTML to the DOM. 4. componentDidMount • The componentDidMount() method is called after the component is rendered. • This is where you run statements that requires that the component is already placed in the DOM.
  • 51. React Lifecycle Updating • The next phase in the lifecycle is when a component is updated. • A component is updated whenever there is a change in the component's state or props. • React has five built-in methods that gets called, in this order, when a component is updated: 1. getDerivedStateFromProps() 2. shouldComponentUpdate() 3. render() 4. getSnapshotBeforeUpdate() 5. componentDidUpdate() The render() method is required and will always be called, the others are optional and will be called if you define them.
  • 52. React Lifecycle Updating: 1. getDerivedStateFromProps • Also at updates the getDerivedStateFromProps method is called. This is the first method that is called when a component gets updated. • This is still the natural place to set the state object based on the initial props. 2. shouldComponentUpdate • In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not. • The default value is true.
  • 53. React Lifecycle Updating: 3. render • The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes. 4. getSnapshotBeforeUpdate • In the getSnapshotBeforeUpdate() method you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update. • If the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error.
  • 54. React Lifecycle Updating: 5. componentDidUpdate • The componentDidUpdate method is called after the component is updated in the DOM.
  • 55. React Lifecycle Unmounting • The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it. • React has only one built-in method that gets called when a component is unmounted: • componentWillUnmount() • The componentWillUnmount method is called when the component is about to be removed from the DOM.
  • 56. Rendering List: React Lists • In React, you will render lists with some type of loop. • The JavaScript map() array method is generally the preferred method. • Example: • Let's render all of the cars from our garage:
  • 58. Rendering List: React Lists • When you run this code in your create-react-app, it will work but you will receive a warning that there is no "key" provided for the list items.
  • 59. Rendering List: React Lists Keys • Keys allow React to keep track of elements. This way, if an item is updated or removed, only that item will be re-rendered instead of the entire list. • Keys need to be unique to each sibling. But they can be duplicated globally. • Generally, the key should be a unique ID assigned to each item.
  • 60. Rendering List: React Lists Keys
  • 61. What are ReactJS Portals? • Portals allow you to render components outside of the normal component hierarchy • The normal component hierarchy is a tree structure, where each component is a child of another component • Portals allow you to break out of this tree structure and render a component anywhere in the DOM • ReactJS components are typically rendered in a tree-like structure. Each component is a child of another component, and the root of the tree is the component that is mounted to the DOM. Portals allow you to break out of this tree structure and render a component anywhere in the the DOM.
  • 62. Why Use Portals? • There are a number of reasons why you might want to use portals in your React application. Some common use cases include: 1. Modals 2. Tooltips 3. Dropdowns 4. Any component that needs to be positioned in a specific location in the DOM
  • 63. Why Use Portals? • Modals: Modals are dialog boxes that appear on top of the rest of the content on a page. Portals are a great way to create modals because they allow you to render the modal content outside of the normal component hierarchy. This means that the modal content won't be affected by the styles or layout of the rest of the page. • Tooltips: Tooltips are small pieces of text that appear when you hover over an element. Portals can be used to render tooltips outside of the normal component hierarchy. This means that the tooltip content won't be affected by the styles or layout of the element that it is associated with.
  • 64. Why Use Portals? • Dropdowns: Dropdowns are menus that appear when you click on a button. Portals can be used to render dropdowns outside of the normal component hierarchy. This means that the dropdown content won't be affected by the styles or layout of the button that it is associated with.
  • 65. How to Use Portals • The createPortal function • The first argument to createPortal is the child component that you want to render • The second argument to createPortal is the DOM element that you want to render the child component into. • Portals are created using the createPortal function. The first argument to createPortal is the child component that you want to render. The second argument to createPortal is the DOM element that you want to render the child component into. • Here is an example of how to use the createPortal function:
  • 66. How to Use Portals • JavaScript • import React from 'react'; • import ReactDOM from 'react-dom'; • const modalRoot = document.getElementById('modal-root'); • function Modal() { • return ( • <div> • <h1>This is a modal</h1> • <button onClick={() => onClose()}>Close</button> • </div> • ); • } • function App() { • const [showModal, setShowModal] = useState(false); • const openModal = () => setShowModal(true); • const onClose = () => setShowModal(false); • return ( • <div> • <button onClick={openModal}>Open Modal</button> • {showModal && ReactDOM.createPortal(<Modal onClose={onClose} />, modalRoot)} • </div> • ); • } • ReactDOM.render(<App />, document.getElementById('root'));
  • 68. Introduction to Bootstrap • Bootstrap is a free and popular HTML, CSS, and JavaScript framework. The following are the features of Bootstrap: • Faster and easier web development • Responsive Website (Web sites that automatically adjust themselves on all devices) • Modern Web Browsers • Mobile-first approach
  • 69. Introduction to Bootstrap • Bootstrap is a free and open-source front-end framework for designing and developing responsive, mobile-first websites. • It consists of pre-designed components like buttons, forms, navigation bars, and more, built with HTML, CSS, and JavaScript. • These components can be easily customized and used to create websites that look great and work well on all devices, from desktops to smartphones.
  • 70. Introduction to Bootstrap • Think of Bootstrap as a toolbox for web developers. • It provides a set of ready-made tools that you can use to build your website quickly and easily, without having to code everything from scratch. • This saves you time and effort, and it also helps to ensure that your website is consistent and well-designed.
  • 71. Features of Bootstrap: • Responsive design: Bootstrap is designed to be mobile-first, which means that your website will look great on all devices, regardless of their screen size. This is important in today's world, where more and more people are using their smartphones and tablets to browse the web. • Easy to use: Bootstrap is very easy to learn, even for beginners. The documentation is clear and concise, and there are plenty of tutorials and examples available online. • Customizable: Bootstrap is highly customizable. You can change the colors, fonts, and styles of the components to match your brand or website design. • Open source: Bootstrap is open source, which means that it is free to use and modify. This makes it a great choice for both personal and commercial projects.
  • 72. Bootstrap Setup • There are two ways to start using Bootstrap 5 on your own web site. 1. Include Bootstrap 5 from a CDN 2. Download Bootstrap 5 from getbootstrap.com
  • 73. Bootstrap Setup 1. Bootstrap 5 CDN • If you don't want to download and host Bootstrap 5 yourself, you can include it from a CDN (Content Delivery Network). • jsDelivr provides CDN support for Bootstrap's CSS and JavaScript:
  • 74. Bootstrap Setup 2. Downloading Bootstrap 5 If you want to download and host Bootstrap 5 yourself, go to https://getbootstrap.com/, and follow the instructions there.
  • 75. Bootstrap Containers • Bootstrap 5 also requires a containing element to wrap site contents. • Containers are used to pad the content inside of them, and there are two container classes available: 1. The .container class provides a responsive fixed width container 2. The .container-fluid class provides a full width container, spanning the entire width of the viewport
  • 77. Bootstrap Grids The grid system is responsive, and the columns will re-arrange automatically depending on the screen size.
  • 79. Bootstrap Grids Basic Structure of a Bootstrap 5 Grid • First example: create a row (<div class="row">). Then, add the desired number of columns (tags with appropriate .col-*-* classes). The first star (*) represents the responsiveness: sm, md, lg, xl or xxl, while the second star represents a number, which should add up to 12 for each row. • Second example: instead of adding a number to each col, let bootstrap handle the layout, to create equal width columns: two "col" elements = 50% width to each col, while three cols = 33.33% width to each col. Four cols = 25% width, etc. You can also use .col-sm|md|lg|xl|xxl to make the columns responsive.
  • 81. Bootstrap Tables A basic Bootstrap 5 table has a light padding and horizontal dividers. • The .table class adds basic styling to a table:
  • 82. Bootstrap Tables Striped Rows • The .table-striped class adds zebra-stripes to a table:
  • 83. Bootstrap Tables Bordered Table • The .table-bordered class adds borders on all sides of the table and cells:
  • 84. Bootstrap Tables Hover Rows • The .table-hover class adds a hover effect (grey background color) on table rows:
  • 85. Bootstrap Tables Black/Dark Table • The .table-dark class adds a black background to the table:
  • 86. Bootstrap Tables Borderless Table • The .table-borderless class removes borders from the table:
  • 87. Bootstrap Buttons • Bootstrap 5 provides different styles of buttons:
  • 88. Bootstrap Buttons • The button classes can be used on <a>, <button>, or <input> elements:
  • 89. Bootstrap Buttons Button Outline • Bootstrap 5 also provides eight outline/bordered buttons. • Move the mouse over them to see an additional "hover" effect:
  • 90. Bootstrap Buttons Button Sizes • Use the .btn-lg class for large buttons or .btn-sm class for small buttons:
  • 91. Bootstrap Buttons Block Level Buttons • To create a block level button that spans the entire width of the parent element, use the .d-grid "helper" class on the parent element:
  • 92. Bootstrap Buttons Spinner Buttons • You can also add "spinners" to a button:
  • 93. Navbars • A navigation bar is a navigation header that is placed at the top of the page.
  • 96. Alerts • Bootstrap provides an easy way to create predefined alert messages. • Alerts are created with the .alert class, followed by one of the contextual classes .alert-success, .alert-info, .alert-warning, .alert-danger, .alert-primary, .alert-secondary, .alert-light or .alert- dark:
  • 98. Bootstrap Carousel • The Carousel is a slideshow for cycling through elements:
  • 99. Bootstrap Carousel • The Carousel is a slideshow for cycling through elements:
  • 100. Bootstrap Carousel • The carousel is a slideshow for cycling through a series of content, built with CSS 3D transforms and a bit of JavaScript. It works with a series of images, text, or custom markup. It also includes support for previous/next controls and indicators.