Unit -V (React)
Unit -V (React)
• React:
• Need of React, Simple React Structure, The Virtual
DOM, React Components, Introducing React
Components, Creating Components in React, Data and
Data Flow in React, Rendering and Life Cycle Methods
in React, Working with forms in React, integrating third
party libraries, Routing in React.
What is React?
• A JavaScript library for building user interfaces (UIs)
function Parent() {
const [name, setName] = useState('John');
return <Child name={name} />;
}
function Child(props) {
return <h1>Hello, {props.name}</h1>;
}
Benefits:
• Simpler data management.
• Easier to trace bugs as data changes happen in a predictable
manner.
Simple React Structure
•Thirdparty libraries— React doesn’t come with tools for data modeling,
HTTP calls, styling libraries, or other common aspects of a frontend
application. This leaves you free to use additional code, modules, or other
tools you prefer in your application. And even though these common
technologies don’t come bundled with React, the broader ecosystem
around React is full of incredibly useful libraries.
•Running a React application— Your React application runs on the
platform you’re building for. It focuses on the web platform and builds a
browser and server based application, but other projects like React
Native and React VR open the possibility of your app running on other
platforms.
Simple React Structure
Full Project Structure
• After running the above commands, your project structure should look something like
this:
• hello-world/
• ├── node_modules/
• ├── public/
• │ └── index.html
• ├── src/
• │ ├── App.css
• │ ├── App.js
• │ ├── index.js
• │ └── logo.svg
• ├── package.json
• ├── package-lock.json
• └── README.md
• • The src/App.js file contains the main code for your app.
• • index.js is where React is hooked into the HTML DOM.
React Lifecycle Methods (Class Components)
1. Node.js and npm (Node Package Manager). You can check if these are installed by
running the following commands in your terminal:
• node -v
• npm -v
•If you don't have Node.js and npm installed, you can download them from nodejs.org.
Step-by-Step Guide FOR CREATING "Hello World" React application
•B)Create-react-app hello-world
(or)
•This will create a new directory called hello-world and set up a boilerplate React application.
•cd hello-world
Step-by-Step Guide FOR CREATING "Hello World" React application
•3. Open src/App.js: The App.js file should look something like this:
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
<h1>Hello World</h1>
</div>
);
}
export default App;
Step-by-Step Guide FOR CREATING "Hello World" React application
•Now that your App.js is set up, start the development server to view your application.
•Run:
•npm start
•This will start the server, and you should see your "Hello World" application in your browser
at http://localhost:3000/.
OUTPUT
Components in React
• The entire application is divided into a small logical group of code, which is known as
components.
• A Component is considered as the core building blocks of a React application. It
makes the task of building UIs much easier.
• Each component exists in the same space, but they work independently from one
another and merge all in a parent component, which will be the final UI of your
application.
• Every React component have their own structure, methods as well as APIs. They can
be reusable as per your need.
• For better understanding, consider the entire UI as a tree. Here, the root is the starting
component, and each of the other pieces becomes branches, which are further divided
into sub-branches.
• In ReactJS, we have mainly two types of components.
1.Functional Components
2.Class Components
Components in React
);
}
export default App;
Example of components(output)
Data and Data Flow in React
• Mutable and immutable state
• state- mutable & props- immutable
• Stateful and stateless components
• Class based component- stateful
• Functional based component-
stateless
• Component communication
• One way data flow
• Parent to child communication
State and Props in Action
• State: Can be updated and triggers re-rendering. State is data that
changes over time, managed within the component. State is
mutable and can trigger re-renders when updated.
state - in class component
useState - in functional component
• The state is an updatable structure that is used to contain data or information about
the component.
• The state in a component can change over time. The change in state over time can
happen as a response to user action or system event.
• A component with the state is known as stateful components.
• It is the heart of the react component which determines the behavior of the component
and how it will render. They are also responsible for making a component dynamic and
interactive.
• A state must be kept as simple as possible. It can be set by using the setState() method
and calling setState() method triggers UI updates.
• A state represents the component's local state or information. It can only be accessed or
modified inside the component or by the component directly.
• To set an initial state before any interaction occurs, we need to use the getInitialState()
method.
React State
• Defining State
• To define a state, you have to first declare a default set of values for defining the
component's initial state.
• To do this, add a class constructor which assigns an initial state using this.state.
• The 'this.state' property can be rendered inside render() method.
Example of State in a Class Component:
import React, { useState } from 'react’; return (
<div style={{ textAlign: 'center',
function Counter() { marginTop: '50px' }}>
// Declare a state variable 'count' and a <h1>Counter: {count}</h1>
function to update it 'setCount' <button
const [count, setCount] = useState(0); onClick={decrement}>Decrement<
/button>
// Function to handle increment <button
const increment = () => { onClick={increment}>Increment</b
setCount(count + 1);
utton>
</div>
};
);
// Function to handle decrement
}
const decrement = () => { export default Counter;
setCount(count - 1);
};
Example of State in a Class Component:
useState Hook:
useState(0) initializes the count state with a value of
0.
setCount is a function used to update the value of
count.
State Updates:
The increment function updates the state by adding 1
to count.
The decrement function updates the state by
subtracting 1 from count.
Dynamic Rendering:
The count value is displayed dynamically in the
<h1> element.
When the state is updated (via setCount), React re-
renders the component to reflect the new state.
Output:
When you click the Increment button, the number
increases. When you click the Decrement button, the
React Hooks (Functional
Components)
• Why Hooks?
• Hooks allow you to use state and lifecycle features in
functional components.
• useState: Manages state in a functional component.
• useEffect: Handles side effects (e.g., fetching data, event
listeners).
React Props
• In React, props (short for "properties") are a way to pass data from a parent
component to a child component.
• Props are read-only, meaning the child component cannot modify them—
they're immutable.
• It is an object which stores the value of attributes of a tag and work similar to
the HTML attributes.
• It gives a way to pass data from one component to other components.
• It is similar to function arguments. Props are passed to the component in the
same way as arguments passed in a function.
• Props are immutable so we cannot modify the props from inside the
component. Inside the components, we can add attributes called props.
• These attributes are available in the component as this.props and can be used
to render dynamic data in our render method.
• When you need immutable data in the component, you have to add props to
reactDom.render() method in the main.js file of your ReactJS project and
used it inside the component in which you need.
React Props(app.js- parent component)
import React from 'react';
import Greeting from './Greeting';
function App() {
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>React Props Example</h1>
{/* Passing props to the Greeting component */}
<Greeting name="Alice" id="111" />
<Greeting name="Bob" id="222"/>
<Greeting name="Charlie" id="333"/>
</div>
);
}
export default App;
React Props(Greeting.js- child component)
function Greeting(props) {
return(
);
React Props(output)
React Props(output)
Explanation:
Passing Props:
In App.js, the Greeting component is used three times with different values for
the name prop (e.g., name="Alice").
This allows Greeting to dynamically render different content based on the props
it receives.
Using Props:
In Greeting.js, the props object is used to access the name property
(props.name).
The value of props.name is injected into the JSX using curly braces {}.
Output: When the application runs, the output will be:
Example:
constructor(props) {
super(props);
this.state = { counter: 0 };
}
2. Mounting (When the component is added to the DOM)
• constructor():
• Initializes state and binds methods.
• Avoid heavy logic here; use it for simple initialization.
• static getDerivedStateFromProps(props, state):
• Syncs state with props before rendering.
• render():
• Returns the JSX to be rendered.
• componentDidMount():
• Invoked after the component is rendered into the DOM.
• Perfect for API calls, subscriptions, or DOM manipulations.
3. Updating (When props or state change)
•shouldComponentUpdate(nextProps, nextState):
•Determines if the component should re-render (used for
optimization).
•getSnapshotBeforeUpdate(prevProps, prevState):
•Captures a snapshot of the DOM before changes (used for
scrolling, etc.).
Example:
componentDidCatch(error, info) {
console.error("Error caught:", error, info);
}
Life cycle method(app.js)
import React from 'react';
class LifeCycleDemo extends React.Component {
// Constructor: Initialize state or bind methods
constructor(props) {
super(props);
this.state = {
count: 0,
};
console.log('Constructor: Component is being created.');
}
// Called after the component is added to the DOM
componentDidMount() {
console.log('componentDidMount: Component has been added to the DOM.');
}
// Called when the component is updated (e.g., state or props change)
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate: Component has been updated.');
console.log('Previous state:', prevState);
console.log('Current state:', this.state);
}
Life cycle method(app.js)
// Called just before the component is removed from the DOM
componentWillUnmount() {
console.log('componentWillUnmount: Component is being removed.');
}
// Event handler to update state
handleIncrement = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }));
};
render() {
console.log('Render: Rendering the component.');
return (
<div>
<h1>React Lifecycle Demo</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.handleIncrement}>Increment</button>
</div>
);
}
}
export default LifeCycleDemo;
Life cycle method(app.js)
Working with forms in React
• Using forms in React
It has better control over the It has limited control over the form
5.
form elements and data. elements and data.
Validating form data in React
• Validating form data in React
• Form validation in React ensures user inputs are correct, complete, and meet required
criteria before submission.
• Types of Validation
• Client-side Validation:
• Performed in the browser.
• Provides instant feedback to the user.
• Reduces server load by catching errors early.
• Server-side Validation:
• Ensures security and data integrity.
• Always validate on the server, even if client-side validation exists.
• Hybrid Approach:
• Combines client and server validation for a robust solution.
Validating form data in React
• Common Validation Rules
• Required Fields: Ensure the user doesn't leave a field empty.
• Format Validation: Check specific patterns (e.g., email,
phone numbers).
• Length Validation: Ensure input meets length requirements
(e.g., password length).
• Range Validation: For numeric or date inputs, validate
min/max limits.
• Custom Rules: Enforce unique application-specific rules (e.g.,
usernames must be unique).
Validating form data in React
• Common Validation Rules
• Required Fields: Ensure the user doesn't leave a field empty.
• Format Validation: Check specific patterns (e.g., email,
phone numbers).
• Length Validation: Ensure input meets length requirements
(e.g., password length).
• Range Validation: For numeric or date inputs, validate
min/max limits.
• Custom Rules: Enforce unique application-specific rules (e.g.,
usernames must be unique).
Validating form data in React
• Simple Validation Workflow
1.User types data into the form.
2.On each change or blur event:
1.Validate the input.
2.Update the state for errors and values.
3.On form submission:
1.Validate all fields.
2.If valid, submit the data to the server.
3.If invalid, prevent submission and show errors.
Validating form(controlled) data in React(email)
//email validation
import React, { useState } from 'react';
export default function ValidatedForm() {
const [email, setEmail] = useState('');
const [error, setError] = useState('');
// Simple validation
if (!/\S+@\S+\.\S+/.test(value)) {
setError('Invalid email address');
} else {
setError('');
}
};
const handleSubmit = (e) => {
e.preventDefault();
if (!error) {
alert('Email submitted successfully....');
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={handleChange} />
</label>
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit" disabled={!!error}>
Submit
</button>
</form>
);
}
Validating form data in React(output)
Example for Uncontrolled Form
import React, { useRef } from "react";
• React Router is used to define multiple routes in the application. When a user types
a specific URL into the browser, and if this URL path matches any 'route' inside the router
file, the user will be redirected to that particular route.
• React Router is a standard library system built on top of the React and used to create
routing in the React application using React Router Package. It provides the synchronous
URL on the browser with data that will be displayed on the web page. It maintains the
standard structure and behavior of the application and mainly used for developing single
page web applications.
• React Router plays an important role to display multiple views in a single page
application. Without React Router, it is not possible to display multiple views in React
applications. Most of the social media websites like Facebook, Instagram uses
React Router for rendering multiple views.
Routing in React (React Router installation)
• React contains three different packages for routing.
1.react-router: It provides the core routing components and functions for the
React Router applications.
2.react-router-native: It is used for mobile applications.
3.react-router-dom: It is used for web applications design.
It is not possible to install react-router directly in your application. To use react
routing, first, you need to install react-router-dom modules in your application. The
below command is used to install react router dom.
2 It is used for developing web applications. It is used for developing mobile applications.
3 It uses a JavaScript library and CSS for It comes with built-in animation libraries.
animations.
It has built-in Navigator library for navigating
4 It uses React-router for navigating web pages.
mobile
applications.
It uses HTML tags. It does not use HTML tags.
5
It can use code components, which It can reuse React Native UI components &
6
saves a lot of valuable time. modules which allow hybrid apps to render natively.