0% found this document useful (0 votes)
20 views62 pages

FS Module-3

The document outlines a course on Full Stack Development focusing on React components, including their types, features, and lifecycle methods. It emphasizes the construction of a web application using the MERN stack, specifically an Issue Tracker application that utilizes CRUD operations. Key concepts include component composition, state management, and the use of props for data handling within the application.

Uploaded by

Chinmayi Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views62 pages

FS Module-3

The document outlines a course on Full Stack Development focusing on React components, including their types, features, and lifecycle methods. It emphasizes the construction of a web application using the MERN stack, specifically an Issue Tracker application that utilizes CRUD operations. Key concepts include component composition, state management, and the use of props for data handling within the application.

Uploaded by

Chinmayi Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Full Stack Development

Manjunath G.S.
Asst. Professor,
Dept. of CS-ICB
Text Books
Web links and Video Lectures (e-Resources):
• https://github.com/vasansr/pro-mern-stack
• https://nptel.ac.in/courses/106106156
• https://archive.nptel.ac.in/courses/106/105/106105084/

• Activity Based Learning


• Course Project- Build Web applications using MERNstack.
Module-3 Syllabus
• React Components: Issue Tracker, React Classes,
Composing Components, Passing Data Using Properties,
Passing Data Using Children, Dynamic Composition,
• React State: Initial State, Async State Initialization,
Updating State, Lifting State Up, Event Handling, Stateless
Components, Designing Components, State vs. Props,
Component Hierarchy, Communication, Stateless
Components
• Textbook 2: Chapter 3, 4
React Components
• React components are the building blocks of a React application.
They are reusable pieces of code that define how a portion of the
user interface should appear and behave.
• There are two main types of components in React:
• 1. Functional Components: Functional components are simple
JavaScript functions that return JSX. They are often used for
presentational purposes.
• Example: function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;}
Contd,…
• 2. Class Components: Class components are more complex and
are defined using ES6 classes. They can hold their own state and
lifecycle methods.
• Example: class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Key features of react components
• Props: Components can receive input via props (properties),
allowing them to be reusable with different data.
• State: Class components can manage their own state, allowing
them to respond to user input and changes in data.
• Lifecycle Methods: Class components have lifecycle methods (like
componentDidMount, componentDidUpdate, and
componentWillUnmount) that let you run code at specific points
in a component’s life.
• Hooks: Functional components can use hooks (like useState,
useEffect) to manage state and side effects.
Issue Tracker
• These applications help you create a bunch of issues or bugs, assign
them to people, and track their statuses.
• These are essentially CRUD applications (Create, Read, Update, and
Delete a record in a database) that manage a list of objects or entities.
• The CRUD pattern is so useful because pretty much all enterprise
applications are built around the CRUD pattern on different entities or
objects.
• In the case of the Issue Tracker, we’ll only deal with a single object or
record, because that’s good enough to depict the pattern.
• Once you grasp the fundamentals of how to implement the CRUD
pattern in MERN, you’ll be able to replicate the pattern and create a
real-life application.
Issue Tracker Contd,…
Here’s the requirement list for the Issue Tracker application, a
simplified or toned-down version of GitHub Issues or Jira:
• The user should be able to view a list of issues, with an ability to
filter the list by various parameters.
• The user should be able to add new issues, by supplying the initial
values of the issue’s fields.
• The user should be able to edit and update an issue by changing its
field values.
• The user should be able delete an issue.
Issue Tracker Contd,…
An issue should have following attributes:
• A title that summarizes the issue (freeform long text)
• An owner to whom the issue is assigned (freeform short text)
• A status indicator (a list of possible status values)
• Creation date (a date, automatically assigned)
• Effort required to address the issue (number of days, a number)
• Estimated completion date or due date (a date, optional)
React Classes
• React classes are used to create real components.
• These classes can then be reused within other components, handle
events, and so much more.
• To start with, let’s replace the Hello World example with a simple
class forming the starting point for the Issue Tracker application.
• React classes are created by extending React.Component, the base
class from which all custom classes must be derived.
• Within the class definition, at the minimum, a render() method is
needed.
• This method is what React calls when it needs to display the
component in the UI.
Contd,…
• Hello World example from a simple element to use a React class
called HelloWorld, extended from React.Component:
...
class HelloWorld extends React.Component {
...
}
...
Contd,…
• within this class, a render() method is needed, which should
return an element. We’ll use the same JSX <div> with the message
as the returned element.
...
render() {
return (
<div title="Outer div">
<h1>{message}</h1>
</div>
);
...
Contd,…
• Move all the code for message construction to within the render()
function so that it remains encapsulated within the scope where it is
needed rather than polluting the global namespace.
...
render() {
const continents = ['Africa','America','Asia','Australia','Europe'];
const helloContinents = Array.from(continents, c => `Hello ${c}!`);
const message = helloContinents.join(' ');
return (
...
);
...
A Simple React Class and Instance
• class HelloWorld extends React.Component {
• render() {
• const continents = ['Africa','America','Asia','Australia','Europe'];
• const helloContinents = Array.from(continents, c => `Hello ${c}!`);
• const message = helloContinents.join(' ');
• return (
• <div title="Outer div">
• <h1>{message}</h1>
• </div>
• );
• }
• }
• const element = <HelloWorld />;
• ReactDOM.render(element, document.getElementById('contents'));
Composing Components
• Component composition is one of the most powerful features of
React.
• This way, the UI can be split into smaller independent pieces so
that each piece can be coded and reasoned in isolation, making it
easier to build and understand a complex UI.
• Using components rather than building the UI in a monolithic
fashion also encourages reuse.
• Composing components in a MERN stack application (MongoDB,
Express, React, Node.js) involves creating reusable and
maintainable parts of your application.
Contd,…
• Smart vs. Dumb Components:
• Smart Components (Container Components): Manage state and logic.
They handle data fetching, state management, and pass data to child
components.
• Dumb Components (Presentational Components): Focus solely on UI
rendering. They receive props and display the data.
• Reusable Components
• Create components that can be reused across your application. For
example, buttons, form inputs, or modal dialogs.Use props to customize
these components, making them versatile.
Contd,…
• State Management
• Use React’s built-in state management or libraries like Redux or Context
API for global state.
• Pass state and dispatch functions as props to child components.
• Props and Composition
• Use props to pass data and callbacks to child components.
• Consider using children prop for rendering nested components or passing
components as props for more flexible composition.
• Handling Side Effects
• Use hooks like useEffect for side effects such as data fetching.
• Keep API calls in container components and pass data down to
presentational components.
Contd,…
• Styling Components
• Use CSS modules, styled-components, or other styling libraries to scope
styles to specific components, avoiding global CSS conflicts.
• Testing Components
• Write unit tests for your components using libraries like Jest and React
Testing Library to ensure they behave as expected.
Structure of the Issue List page
Contd,…
• ...
• class IssueFilter extends React.Component {
• render() {
• return (
• <div>This is a placeholder for the issue filter.</div>
• );
• }
•}
• ...
Contd,…
• ...
• class IssueTable extends React.Component {
• ...
• <div>This is a placeholder for a table of issues.</div>
• ...
• class IssueAdd extends React.Component {
• ...
• <div>This is a placeholder for a form to add an issue.</div>
• ...
Contd,…
• ...
• class IssueList extends React.Component {
•}
• ...
Contd,…
• class IssueFilter extends React.Component {
• render() {
• return (
• <div>This is a placeholder for the issue filter.</div>
• );
• }
• }
• class IssueTable extends React.Component {
• render() {
• return (
• <div>This is a placeholder for a table of issues.</div>
• );
• }
• }
Contd,…
• class IssueAdd extends React.Component {
• render() {
• return (
• <div>This is a placeholder for a form to add an issue.</div>
• );
• }
•}
Contd,…
• class IssueList extends React.Component {
• render() {
• return (
• <React.Fragment>
• <h1>Issue Tracker</h1>
• <IssueFilter />
• <hr />
• <IssueTable />
• <hr />
• <IssueAdd />
• </React.Fragment>
• );
• }
• }
• const element = <IssueList />;
• ReactDOM.render(element, document.getElementById('contents'));
Contd,…
React Classes
• In React, classes were commonly used to create components
before the introduction of hooks in React 16.8.
1. Defining a Class Component: A class component is defined by
extending React.Component.
React Classes
React Classes
2. State Management
• State is a built-in object that holds the data of the component.
• You initialize state in the constructor using this.state = {}.
• Use this.setState() to update the state, which triggers a re-render
of the component.
React Classes
3. Lifecycle Methods
Class components have lifecycle methods that allow you to run code
at specific points in a component's lifetime:

componentDidMount(): Invoked immediately after a component is


mounted.
componentDidUpdate(prevProps, prevState): Invoked immediately
after updating occurs.
componentWillUnmount(): Invoked immediately before a
component is unmounted and destroyed.
React Classes
4. Handling Events
Event handlers in class components need to be bound to the class
instance, usually done in the constructor:
React Classes
5. Props
Props are passed to components similar to function arguments. You
can access props using this.props:
Passing Data Using Properties
• Composing components without any variables is not so
interesting.
• It should be possible to pass different input data from a parent
component to a child component and make it render differently on
different instances.
• In the Issue Tracker application, one such component that can be
instantiated with different inputs is a table-row showing an
individual issue.
Passing Data Using Properties
Passing Props from Parent to Child
• import React from 'react';
• // Child Component
• const ChildComponent = (props) => {
• return <h1>Hello, {props.name}!</h1>;
• };

• // Parent Component
• const ParentComponent = () => {
• return <ChildComponent name="Alice" />;
• };
• export default ParentComponent;
Accessing Props in Class Components
• import React from 'react';
• class ChildComponent extends React.Component {
• render() {
• return <h1>Hello, {this.props.name}!</h1>;
• }
• }

• class ParentComponent extends React.Component {


• render() {
• return <ChildComponent name="Bob" />;
• }
• }
• export default ParentComponent;
Contd,…
Default Props
• ChildComponent.defaultProps = {
• name: 'Guest'
• };

Prop Types
• import PropTypes from 'prop-types';
• ChildComponent.propTypes = {
• name: PropTypes.string.isRequired,
• };
Passing Functions as Props
• const ChildComponent = ({ onClick }) => {
• return <button onClick={onClick}>Click Me!</button>;
• };

• const ParentComponent = () => {


• const handleClick = () => {
• alert('Button was clicked!');
• };

• return <ChildComponent onClick={handleClick} />;


• };
Passing Multiple Props
• const ChildComponent = ({ name, age }) => {
• return <p>{name} is {age} years old.</p>;
• };

• const ParentComponent = () => {


• return <ChildComponent name="Charlie" age={10} />;
• };
Dynamic Composition
• Dynamic composition in React components refers to the ability to
combine and compose components in flexible ways based on the
application's state, props, or any other criteria.
1. Using Props to Control Composition
• You can use props to determine which components to render.
Dynamic Composition
2. Render Props Pattern
• Using a render prop allows a component to share its state with a
child component, which can decide how to render itself based on
that state.
Dynamic Composition
3. Children as a Function
• This pattern allows you to pass a function as children to a
component, giving it the flexibility to render dynamically based on
internal state or props.
Dynamic Composition
4. Higher-Order Components (HOCs)
• HOCs are functions that take a component and return a new
component, enabling dynamic behavior and composition.
Dynamic Composition
Dynamic Composition
React State
• To make components that respond to user input and other events,
React uses a data structure called state in the component.
• The state essentially holds the data, something that can change, as
opposed to the immutable properties in the form of props that you
saw earlier.
• This state needs to be used in the render() method to build the
view.
• It is only the change of state that can change the view.
• When data or the state changes, React automatically rerenders the
view to show the new changed data.
Initial State
• The state of a component is captured in a variable called this.state in
the component’s class, which should be an object consisting of one or
more key-value pairs, where each key is a state variable name and the
value is the current value of that variable.
• React does not specify what needs to go into the state, but it is useful to
store in the state anything that affects the rendered view and can
change due to any event.
• These are typically events generated due to user interaction.
• IssueTable component, the list of issues being displayed is definitely
one such piece of data that both affects the rendered view and can also
change when an issue is added, edited, or deleted.
• The array of issues is therefore an ideal state variable.
Async State Initialization
• The state can only be assigned a value in the constructor. After
that, the state can be modified, but only via a call to
React.Component’s this.setState() method.
• This method takes in one argument, which is an object containing
all the changed state variables and their values.
• The only state variable that we have is the one called issues, which
can be set to any list of issues in a call to this.setState() like this:
• ...
• this.setState({ issues: newIssues });
• ...
Async State Initialization
• let’s call this.setState() with the static array of initial issues like
this:
• ...
• loadData() {
• setTimeout(() => {
• this.setState({ issues: initialIssues });
• }, 500);
• }
• ...
Async State Initialization
Updating State
• To start, let’s add a method in IssueTable to add a new issue.
• This can take in as an argument an issue object, to which we’ll
assign a new ID and set the creation date. The new ID can be
calculated from the existing length of the array.
• ...
• createIssue(issue) {
• issue.id = this.state.issues.length + 1;
• issue.created = new Date();
• }
• ...
Updating State
• The state variable cannot be set directly, nor can it be mutated directly
• ...
• this.state.issues.push(issue); // incorrect!
• ...
• The reason is that React does not automatically identify such changes to
the state because it is a plain JavaScript variable.
• ...
• issues = this.state.issues;
• issues.push(issue); // same as this.state.issues.push()!
• this.setState({ issues: issues });
• ...
Updating State
Setting state and passing data as props
Lifting State Up
• Lifting state up is a common pattern in React where you move the
state management to the closest common ancestor of components
that need to share the state.
• This allows multiple components to access and update the same
state, facilitating communication between sibling components.
• The main reason to lift state up is when you have multiple
components that need to interact with or reflect the same state.
• Instead of each component managing its own copy of the state, you
move the state management to their closest common ancestor.
• This way, the state can be passed down to the child components,
ensuring consistency across them.
Lifting State Up
• Lifting state up involves two main steps:
• Define the state in the parent component.
• Pass the state down to child components as props.
• Pass setter functions down to child components so they can
update the state.
• Basic Example
• Imagine a scenario where you have a parent component and two
child components. Each child needs to access or modify a piece of
shared state. Lifting state up ensures that both children can
communicate via their shared parent.
Benefits Lifting State Up
• Shared State: Both children can access and modify the same state,
ensuring synchronization between them.
• Single Source of Truth: By keeping the state in one place, it
becomes easier to manage and debug.
• Clearer Data Flow: Data flow is explicit because state is passed
down through props from the parent component, making it clear
where the state is coming from and how it is being modified.
• Lifting state up is an essential concept in React for managing shared
state between multiple components.
• By placing state in the common ancestor and passing it down as
props, React helps ensure that the data flows predictably through
your components.
Event Handling
• ...
• <div>This is a placeholder for a form to add an issue.</div>
• <form>
• <input type="text" name="owner" placeholder="Owner" />
• <input type="text" name="title" placeholder="Title" />
• <button>Add</button>
• </form>
• ...
• At this point, we can remove the timer that creates an issue from the constructor.
• ...
• constructor() {
• super();
• setTimeout(() => {
• this.props.createIssue(sampleIssue);
• }, 2000);
• }
• ...
Event Handling
Event Handling
Thank You

You might also like