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
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
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:
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
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
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:
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:
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":
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, {}.
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.
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.
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.
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:
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
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.
89. Bootstrap Buttons
Button Outline
• Bootstrap 5 also provides eight outline/bordered buttons.
• Move the mouse over them to see an additional "hover" effect:
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:
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:
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.