03 ReactJS
03 ReactJS
Module 03
ADC502 : Web Development
1
What is React
• React is a popular JavaScript library for building user
interfaces (UIs) and web applications.
• It was developed and is maintained by Facebook and a
community of individual developers and companies.
• React is the view layer of an MVC application (Model View
Controller)
• React is often used for building single-page applications
(SPAs) and is known for its efficiency and performance.
2
Prerequisites
• HTML/CSS:
• basic understanding of HTML and CSS for building web interfaces.
• JavaScript:
• Familiarity with JavaScript, including ES6 (ECMAScript 2015)
features.
3
Node.js and npm
• Install Node.js and npm (Node Package Manager).
• It can be downloaded them from the official website:
https://nodejs.org/
4
Create a React Application
• Create React App is a popular tool to set up a React development
environment quickly.
• To start a new React project using Create React App, open terminal
and run the following command:
npx create-react-app my-react-app
• This command will create a new directory called my-react-app with a
basic React project structure.
5
Understanding the Project Structure
• Key folders and files include:
• src/: This is where your application's source code
resides.
• src/index.js: The entry point of your application.
• src/App.js: The main component of your application.
• public/index.html: The HTML file where your React
app is mounted.
• package.json: Contains project dependencies and
scripts.
6
Run the Development Server
• Change into your project directory:
cd my-react-app
• This will open a new browser window with the React app running at
http://localhost:3000.
7
8
Make ‘Hello World’ app
• Open the src/App.js file in a code editor.
• You'll see the default React component created by Create React App.
• Replace its contents with the following code
import React from 'react';
function App() {
return (
<div className="App">
<h1>Hello, React!</h1>
</div>
);
}
export default App; 9
Add Custom Style
• This step is optional.
• update src/App.css with following content
.App {
text-align: center;
}
h1 {
color: #414141;
}
10
Import CSS
• Import the CSS file into your App.js component:
import './App.css';
11
12
React Components
13
React Components
• In React, a component is a reusable building block that
encapsulates a part of a user interface (UI) and its behavior.
• Components are the fundamental units of a React
application and can be thought of as self-contained, isolated
pieces of code that can be composed together to build
complex UIs.
• There are two main types of components in React:
• Function Components
• Class Components
14
Function Components
• These are also known as stateless functional components.
• Function components are defined as JavaScript functions that take a
set of input properties (called props) and return React elements that
describe what should be rendered on the screen.
• Function components are typically used for simple, stateless parts of a
UI.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
15
Class Components
• Class components are defined as ES6 classes that extend the
React.Component class.
• They have a render() method that returns the UI elements.
• Class components are used when you need to manage state or use
lifecycle methods.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
16
Components with other components
• Example of how to use a component within another component:
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}
• In this example, the Welcome component is used twice within the App
component. Each instance of Welcome receives a different name prop.
17
Component Tree
• Components are the building blocks of a
React application, and a typical React
application is structured as a tree of
components, with a single root component at
the top.
• This component tree represents the entire UI
of the application and is what makes React
applications highly modular, maintainable,
and easy to reason about.
18
State and Props
19
State and Props
• Components can have properties, called props, which allow
passing data from a parent component to a child
component.
• These props are read-only and should not be modified
within the child component.
• Components can also have their own internal state, which
allows them to manage and update data that is specific to
that component.
• Class components can define and manage state using the
setState method, while functional components can use
React Hooks like useState to manage state.
20
State and Props : Example
• In the following example, we'll create a simple "Counter" component
that takes a starting value as a prop and allows you to increment and
decrement the counter using buttons.
• The counter value will be stored in the component's state.
21
State and Props : Example
import React, { Component } from 'react'; // Function to decrement the counter.
decrement = () => {
class Counter extends Component { this.setState({ count: this.state.count - 1 });
constructor(props) { };
super(props);
render() {
// Initialize the component's state with the starting value return (
received as a prop.
<div>
this.state = {
<h2>Counter Value: {this.state.count}</h2>
count: props.initialValue,
<button onClick={this.increment}>Increment</button>
};
<button onClick={this.decrement}>Decrement</button>
}
</div>
// Function to increment the counter.
);
increment = () => {
}
this.setState({ count: this.state.count + 1 });
}
};
22
State and Props : Example
• The Counter component receives an initialValue prop, which
is used to set the initial state of the counter.
• Inside the constructor, we initialize the component's state
with the initialValue prop.
• We define two methods, increment and decrement, to
update the state when the respective buttons are clicked.
These methods use this.setState to modify the count
property in the component's state.
23
State and Props : Example
• In the render method, we display the current counter value
from the component's state along with "Increment" and
"Decrement" buttons. When these buttons are clicked, the
increment or decrement methods are called to update the
state, causing the component to re-render with the new count
value.
• You can use this Counter component in another component or
in your App component, passing different initial values as
props to create multiple counters with different starting values.
24
State and Props : Example
import React from 'react'; In this App component,
import Counter from './Counter';
we use the Counter
function App() {
return ( component three times
<div> with different initial
<Counter initialValue={0} />
values, demonstrating the
<Counter initialValue={5} />
<Counter initialValue={10} />
use of props and
</div> component state in React.
);
}
export default App;
25
FAQ about Components, state and
props
1. What is the difference between props and state in React?
• Props (Properties): Props are used to pass data from a parent
component to a child component. They are immutable and
read-only within the child component. Props are used for
data that doesn't change within the child component.
• State: State is used to manage and store data that can change
within a component. Components can have their own state,
and changes to state trigger re-renders. State should be used
for data that will change over time within the component.
26
FAQ about Components, state and
props
2. Can props be changed within a component?
• No, props cannot be changed within a component. They are immutable
and read-only. If you need to modify data within a component, you
should use component state instead.
3. How do you pass props to a component?
• Props are passed to a component when you use that component in JSX.
You specify the prop values as attributes. For example:
<MyComponent name="John" age={30} />
• In this example, name and age are props being passed to
MyComponent.
27
FAQ about Components, state and
props
4. How can a child component communicate with its parent component?
• Child components can communicate with their parent components by
invoking callback functions passed to them as props.
• The child component can call these functions, passing data to the parent
component.
5. When should you use component state versus props?
• Use props when you have data that is passed from a parent component and
should not be modified within the child component.
• Use state when you need to manage and update data within a component,
especially when that data can change over time due to user interactions or
other factors.
28
FAQ about Components, state and
props
6. Can a component have both state and props?
• Yes, a component can have both state and props.
• Props are used for data that comes from outside the component,
while state is used for managing data within the component.
7. What is the purpose of the setState method?
• The setState method is used to update a component's state.
• When you call setState, React re-renders the component with the
new state, reflecting any changes in the UI.
29
FAQ about Components, state and
props
8. Can you directly modify state using assignment in React?
• No, you should never directly modify the state using assignment. Always use
the setState method to update state.
• Direct assignment will not trigger a re-render, and React's state management
won't work as expected.
9. What are the best practices for passing complex data as props?
• It's a good practice to pass down complex data as props in a structured
format, such as objects or arrays.
• This makes the data easier to work with in the child component. If the data is
deeply nested, consider using libraries like Lodash or functions like map to
extract the required data.
30
FAQ about Components, state and
props
10. What is the role of the constructor in a React component?
• The `constructor` is a special method used in class components to
initialize the component's state and bind event handlers.
• It is typically used to set the initial state and perform any setup needed
before rendering.
11. What is the purpose of components in React?
• Components in React promote code reusability, maintainability, and a
modular structure.
• They allow you to break down complex UIs into smaller, manageable
pieces.
31
FAQ about Components, state and
props
12. What is state in React components?
• State is a way to manage and store data that can change within a
component.
• It allows components to be dynamic and respond to user interactions or
other triggers.
• Class components have a state object, while functional components can
use React hooks to manage state.
13. How do you render a component in React?
• Components are rendered by invoking them within JSX. For example,
<MyComponent /> is used to render the MyComponent component.
32
FAQ about Components, state and
props
14. How can components communicate with each other in React?
• Components can communicate by passing data through props. Parent
components can pass data and functions as props to child components.
• For more complex communication, you can use state management
libraries like Redux or context API.
15. Can components have their own styles?
• Yes, components can have their own styles.
• You can apply styles using CSS, CSS modules, or CSS-in-JS libraries like
styled-components.
33
FAQ about Components, state and
props
16. How can components be tested in React?
• Components can be tested using testing libraries like Jest and React
Testing Library. You can write unit tests to ensure that your
components behave correctly.
17. What is the lifecycle of a class component in React?
• Class components have several lifecycle methods, including
componentDidMount, componentDidUpdate, and
componentWillUnmount, which allow you to perform actions at
different stages of a component's existence.
34
Component Lifecycle
35
Component Lifecycle
• The React component lifecycle refers to the various stages a
React component goes through from its creation to its removal
from the DOM.
• It's important to understand these stages to manage component
behavior and side effects effectively.
• A component’s lifecycle is broadly classified into four parts:
• initialization
• mounting
• updating
• unmounting
36
Initialization
• In the initialization class ExampleComponent extends
React.Component {
phase, the constructor of constructor(props) {
the component is called. super(props);
• State can be initialized in this.state = {
the constructor. count: 0
• The component is not yet };
}
mounted to the DOM.
// ...
}
37
Mounting
• After initialization, the component componentDidMount() {
// Example: Fetch data from an API
is mounted into the DOM.
after the component is mounted.
• The componentDidMount
lifecycle method is called once fetch('https://api.example.com/data')
after mounting, making it an ideal .then(response => response.json())
place for data fetching and .then(data => {
this.setState({ data });
initialization that requires access
});
to the DOM.
}
38
Updating
• When a component's componentDidUpdate(prevProps, prevState) {
// Example: Check if props or state changed and
state or props change, it perform actions accordingly.
triggers the update if (this.props.someProp !== prevProps.someProp) {
phase. // Handle prop change
• The }
if (this.state.someState !== prevState.someState) {
componentDidUpdate
// Handle state change
lifecycle method is called }
after each update, }
allowing for side effects.
39
Unmounting
• If a component is removed from componentWillUnmount() {
the DOM, the // Example: Cleanup operations
componentWillUnmount before unmounting the component.
method is called.
// Cancel network requests,
• This is the place to clean up remove event listeners, etc.
resources, such as canceling
network requests or removing }
event listeners.
40
UI design in React
41
UI design in react
• Designing user interfaces (UI) in React involves creating visually
appealing and interactive components that make up your web
application.
• React itself doesn't prescribe a specific way to design UIs; instead, it
provides a framework for building UI components.
42
Principles of UI design in React
• Component-Based Design:
• Break your UI into small, reusable components. Each component should have
a single responsibility and be self-contained.
• Components should follow the Single Responsibility Principle (SRP), meaning
they should do one thing well.
• React's JSX:
• Use JSX (JavaScript XML) to define the structure and layout of your UI
components. JSX allows you to write HTML-like code within your JavaScript.
• Leverage JSX's ability to embed JavaScript expressions within curly braces,
enabling dynamic content rendering.
43
Principles of UI design in React
• CSS Styling:
• Apply CSS styles to your components to control their appearance. You can use
traditional CSS, CSS modules, or CSS-in-JS libraries like styled-components.
• Consider using a CSS framework like Bootstrap or Material-UI to streamline
styling.
• Responsive Design:
• Ensure your UI is responsive and adapts to different screen sizes and devices.
Use CSS media queries to apply styles for various breakpoints.
• Consider using CSS Flexbox or Grid for creating flexible and responsive
layouts.
44
Principles of UI design in React
• User Experience (UX):
• Focus on creating a positive user experience. Keep the user flow intuitive and
efficient.
• Use React's state management to handle dynamic UI elements that respond
to user interactions.
• Accessibility:
• Implement accessibility best practices to ensure your UI is usable by
individuals with disabilities. Use semantic HTML elements and provide alt text
for images.
• Test your UI with screen readers and other assistive technologies.
45
Principles of UI design in React
• Component Libraries:
• Consider using component libraries like Material-UI, Ant Design, or Semantic
UI for pre-designed, customizable UI components.
• These libraries can save development time and maintain consistency.
• State Management:
• Use React's state management to control the data and dynamic behavior of
your components.
• Libraries like Redux and Mobx can help manage complex application state.
46
Principles of UI design in React
• Testing:
• Write unit tests for your components to ensure they render as expected and
behave correctly.
• Use testing libraries like Jest and React Testing Library for testing React
components.
• Performance Optimization:
• Optimize your UI for performance. Avoid unnecessary re-renders by using
React's PureComponent or memoization techniques.
• Lazy loading and code splitting can help reduce initial load times.
47
Principles of UI design in React
• Design Tools:
• Utilize design tools like Sketch, Figma, or Adobe XD to create wireframes and
mockups before implementing them in React.
• Collaborate with designers to ensure the UI matches the desired look and
feel.
• Feedback and Iteration:
• Collect feedback from users and stakeholders, and be open to making
improvements.
• Continuously iterate and refine your UI based on feedback and changing
requirements.
48
UI design in React
• UI design is an ongoing process, and it's essential to strike a balance
between aesthetics and functionality.
• React's component-based architecture and ecosystem of libraries and
tools provide a solid foundation for building well-designed user
interfaces.
49
Forms in react
50
Forms in react
• Handling forms in React involves creating and
managing form elements and their data within React
components.
• React provides a controlled component approach,
where form elements like input fields, checkboxes,
and radio buttons are controlled by React state.
51
Working with forms in React
• Start by creating a React component that will render your form.
• This component should include the form elements you need, such as input fields, select
boxes, and buttons
class MyForm extends Component {
constructor(props) {
super(props);
this.state = {
// Initialize state properties to store form data.
username: '',
email: '',
};
} 52
Working with forms in React <label>
Email:
render() { <input
return ( type="email"
<form> name="email"
<label> value={this.state.email}
Username:
onChange={this.handleChange}
<input
/>
type="text"
</label>
name="username"
<br />
value={this.state.username}
<button
type="submit">Submit</button>
onChange={this.handleChange}
/> </form>
</label> );
<br /> }
}
53
Working with forms in React
• Controlled Components
• Notice that each input field has a value attribute set
to this.state.username or this.state.email.
• This makes these inputs controlled components,
meaning React controls their values.
54
Working with forms in React
• Handling Form Changes
• Create an event handler (handleChange in this case) to
update the component's state when the user interacts
with the form.
57
Working with forms in React
• Handling Form Submission:
• Within the submit event handler, you can access the form data from this.state
and perform actions such as sending the data to a server using AJAX requests or
updating the application's state.
• Validation and Error Handling:
• Implement form validation to ensure that user inputs meet your criteria. You can
display validation errors by updating the component's state and rendering error
messages.
• Form Libraries:
• For complex forms or more advanced features like form validation and state
management, consider using form libraries like Formik or React Hook Form,
which simplify form handling in React applications.
58
Forms in React Example
RegistrationForm.js
59
React Router
60
React Router
• React Router is a widely-used library for routing in single-page
applications (SPAs) built with React.
• The main purpose of React Router is to enable the creation of a multi-
page-like navigation experience within a single-page application.
• In SPAs, the entire application loads as a single HTML page, and React
Router helps manage the URL and rendering different components
based on the URL, giving the illusion of navigating between multiple
pages.
61
Benefits of React Router
1. Client-Side Routing:
• React Router enables client-side routing by allowing you to define
routes within your SPA. Instead of requesting new pages from the
server, React Router manages route changes entirely on the client side.
This results in a more fluid and faster user experience as only the
relevant components are loaded, and there's no full page reload.
2. Improved User Experience:
• With React Router, users can navigate through your SPA without waiting
for the server to respond, providing a more responsive and interactive
experience. It allows for smooth transitions between different views or
components, providing a native app-like feel to your web application.
62
Benefits of React Router
3. Code Splitting and Lazy Loading:
• React Router supports code splitting, which means you can load only
the components required for a specific route. This reduces the initial
load time and ensures that your application remains performant, even
as it grows. Components are loaded on-demand, improving page load
times.
4. SEO-Friendly:
• React Router offers server-side rendering (SSR) support, which is
essential for SEO. Search engine crawlers can better index the content
of your SPA because the routes are managed on the server as well. This
improves the discoverability of your web application.
63
Benefits of React Router
5. Nested Routing:
• React Router allows you to define nested routes within your
application, mirroring the hierarchy of your components. This is
particularly useful for complex applications with multiple views
and layouts. It provides a clear way to organize your code and
routes.
6. Centralized Route Configuration:
• React Router promotes a centralized way of managing route
configuration. You define your routes in one place, making it easier
to maintain and update your application's navigation structure.
64
Benefits of React Router
7. URL Parameters and Dynamic Routing:
• React Router supports dynamic routing, allowing you to create
routes with placeholders for URL parameters. This is useful for
creating flexible and reusable components that can adapt to
different data or contexts.
8. History and Navigation Handling:
• React Router provides easy-to-use components and hooks for
managing browser history and navigation. You can
programmatically navigate between routes and handle various
navigation events with ease.
65
Scenario: An Online Shopping
Platform
• Imagine you are building an online shopping platform as a single-page
application (SPA) using React.
• Users need to be able to navigate through various sections of the
platform, such as the product catalog, shopping cart, and user
account settings.
• This scenario is a perfect fit for React Router.
66
Scenario: An Online Shopping
Platform
• Installation:
npm install react-router-dom
# or
yarn add react-router-dom
• Setting Up Routes:
• Define the routes for your application. In the context of an online shopping
platform, you might have routes for the home page, product catalog,
shopping cart, and user account settings. You can set up your routes in a
separate file, for example, "Routes.js":
67
// Routes.js
import { Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import ProductCatalog from './components/ProductCatalog';
import ShoppingCart from './components/ShoppingCart';
import AccountSettings from './components/AccountSettings';
const Routes = () => {
return (
<Switch>
<Route path="/" exact component={Home} />
<Route path="/catalog" component={ProductCatalog} />
<Route path="/cart" component={ShoppingCart} />
<Route path="/account" component={AccountSettings} />
</Switch>
);
};
68
export default Routes;
Scenario: An Online Shopping
Platform
• Integrate the routes you've defined into your main "App" component.
You can use the "BrowserRouter" to wrap your application, which
provides the necessary context for routing:
69
// App.js
import { BrowserRouter as Router } from 'react-router-dom';
import Routes from './Routes';
function App() {
return (
<Router>
<div className="App">
<header> <!-- Header content --> </header>
<main>
<Routes />
</main>
<footer> <!-- Footer content --> </footer>
</div>
</Router>
);
}
70
export default App;
Scenario: An Online Shopping
Platform
• Navigation and Links: Within your components, you can use the "Link" component to create
navigation links. For instance, in your shopping cart component, you might have a link to
navigate back to the product catalog:
// ShoppingCart.js
import { Link } from 'react-router-dom';
function ShoppingCart() {
return (
<div>
<!-- Shopping cart content -->
<Link to="/catalog">Continue Shopping</Link>
</div>
); 71
}
Scenario: An Online Shopping
Platform
• Dynamic Routing: React Router also allows for dynamic routing. For
example, you can create a route that displays the details of a specific
product by using URL parameters:
// Routes.js
<Route path="/product/:productId" component={ProductDetails} />
72
Scenario: An Online Shopping
Platform
• Guarded Routes and Authorization
• Implement guarded routes to restrict access to certain parts of your
application, such as user account settings.
• You can use React Router's "PrivateRoute" to check if a user is authenticated
before allowing access to protected routes.
73
Event handling in react
74
Event handling in react
• Event handling in React is a fundamental aspect of building interactive
user interfaces.
• It involves defining and managing event listeners to respond to user
interactions, such as clicks, input changes, and keyboard presses.
1. Event Definition:
• Identify the event you want to handle.
• This could be a button click, a form submission, a mouse hover, a
keyboard input, or any other user interaction.
75
Event handling in react
2. Event Handler Function:
• Create a JavaScript function that will be called when the event occurs.
• This function will handle the event and define the behavior he wants
to execute in response.
function handleClick() {
// Define what happens when the event occurs
}
76
Event handling in react
3. Attaching Event Listeners:
• Attach the event listener to the React element where you want to
capture the event. In JSX, you specify the event and the corresponding
handler function.
77
Event handling in react
4. Event Handling Function
• Inside the event handler function, you can access event information
and define the desired behavior in response to the event. For
instance, you can update component state, make API requests, or
navigate to a different page.
function handleClick() {
// Update component state
this.setState({ count: this.state.count + 1 });
}
78
Event handling in react
5. Event Parameters
• Depending on the event type, you may receive event parameters, such as
the event object, which contains information about the event, including the
target element and event details.
function handleClick(event) {
// Access event properties
const target = event.target;
// ...
}
79
Event handling in react
6. Preventing Default Behavior
• In some cases, you may need to prevent the default behavior of an
event. For example, to prevent a form from submitting and causing a
page refresh, he can use event.preventDefault().
function handleSubmit(event) {
event.preventDefault();
// Handle form submission without page refresh
}
80
Event handling in react
7. Binding Event Handlers
• Be aware of how the event handlers are bound to this.
• In class components, you may need to use arrow functions or explicitly bind
the handler to this in the constructor.
• In functional components, you can use the useState and useEffect hooks to
manage state and side effects.
8. Testing and Debugging
• Thoroughly test and debug your event handling logic to ensure it behaves as
expected.
• Use tools like React DevTools and browser developer tools to inspect and
debug events
81
Event handling in react
9. Event Propagation:
• Understand event propagation and bubbling in React.
• You can choose whether to stop an event from propagating up the
component hierarchy or allow it to continue to parent components.
82
Binding Event Handlers
Arrow Functions
One common approach is to use arrow functions for event handlers.
Arrow functions inherit the this value from their containing scope, which means they preserve
the correct context:
85
Binding Event Handlers : Functional
Components
import React, { useState, useEffect } from 'react';
function MyFunctionalComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// Side effect code here
}, [count]);
86
Binding Event Handlers : Functional
Components
const handleClick = () => {
// 'count' is accessible without 'this'
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
87
More to follow!
We will learn more about React in Module 6.
88