Unit-5
Unit-5
What is ReactJS?
ReactJS is a free, open-source JavaScript library for
building User Interfaces(UIs) for web
applications ,which was developed by Facebook .
It is used to build single-page applications and allows
you to create reusable UI components.
Need of react
React is an excellent tool for building websites quickly.
React works on components which makes it easy to
reuse the components in other builds. It also allows
you to create new features without having to start from
scratch, as you can reuse the codes and save time and
money as well
Features of ReactJS
Component Based Architecture: Reusable
components of code that represents different
parts of user interface.
JSX: JavaScript XML, a syntax extension for
JavaScript, that allows us to write HTML in
JavaScript Code.
Virtual DOM: ReactJS uses Virtual DOM.
With Virtual DOM, only the component or part
that changes gets updated in Real DOM.
State Management: State is managed within the
component, and when it changes, the components
re-renders.
One Way Data Binding: Data is passed from parent
to child components through props.
React Hooks: Hooks like useState, useEffect and
useContext.... make it easier to write more clean
and readable code.
Advantages of React
1. Easy To Learn:- React can be learned quickly and
easily because it doesn’t require special skills or
experience—just basic HTML, CSS, and JavaScript
knowledge.
2.Faster To Build:- Faster To Build Because of its
component-based approach and virtual DOM
3.Efficient Code Reuse Facility:- The major
advantage of components in this JavaScript
library is that you can re-use them on any
platform
Difference between react and angular
React and angular both are used to create single page
application using component.
React Angular
javascript typescript
React used to create Angular used to create single
single page page application using
application using component.
component.
Installation of ReactJS:-
Create React App (CRA) has been officially deprecated
in 2023 and is no longer the recommended method for
starting React projects. Instead, tools
like Vite or Next.js are now preferred for creating React
applications due to better performance and modern
features. However, if you still want to use it, follow
these steps:
1. Install CRA Globally
npm install -g create-react-app
2. Verify the installation
It will globally install react app for you. To check
everything went well run the command
create-react-app --version
3.Create the React App Using CRA Command
If you’re using CRA:
Run the following command to create a React app:
npx create-react-app reactfirst
Run the React App
Start the development server by running:
npm start
Once you run the above command, a new browser tab
will open, displaying the default React page with the
React logo.
Write a program in Angular to display Hello world
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,
document.getElementById('root'));
App.js
import React from 'react';
function App() {
return <h1>Hello, World!</h1>;
}
export default App;
Output:-
Virtual DOM:
The Virtual DOM (VDOM) is a lightweight, in-memory
representation of the real DOM (Document Object
Model). It helps React manage UI updates more
efficiently by keeping a virtual version of the UI in
memory. When changes occur, React updates only the
necessary parts of the real DOM, instead of re-
rendering everything.
Example Program:-
Apple.jsx
function Apple(){
return (
<h1>This is my component.</h1>
)
}
export default Apple;
App.js
import logo from './logo.svg';
import './App.css';
import Apple from './Apple';
function App() {
return (
<div className="App">
<Apple />
</div>
);
}
export default App;
output:-
2)class component:-
To define the class component we have to first create a
class and extend ReactComponent class.
Class components are ES6 classes that return
JSX .Below is a class component which is similar to
Welcome function as given in Functional component.
Example program:-
Welcome.js
import React,{Component} from 'react';
class Welcome extends Component{
render() {
return <h1>welcome to lab </h1>
}
}
export default Welcome;
App.js
import './App.css';
import Welcome from './components/Welcome';
function App() {
return (
<div className="Welcome">
<Welcome />
</div>
);
}
export default App;
Props:-
The props stand for properties.These are the
arguments that are passed to the react components.
// App.js
import React from 'react';
import Greeting from './Greeting';
function App() {
return (
<div>
<h1>Welcome to React Props Example</h1>
<Greeting name="John" />
</div>
);
}
export default App;
1. Parent to Child:
Data is passed from parent components to child
components through props. The parent component
owns the state, and it passes down relevant data to its
child components as props.
Props (short for "properties") in React are a mechanism
for passing data from a parent component to its child
component as a set of read-only attributes.
Example program: Sending the data from parent to
child as "Hello, this is data from the parent to child".
function handleUpdateCounter() {
setCounter(counter + 1);
}
return (
<>
<h1>Counter value: {counter}</h1>
<button
onClick={handleUpdateCounter}>Change</button>
</>
);
}
export default App;
App.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const
root=ReactDOM.createRoot(document.getElementById
('root'));
root.render(
<App />
);
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => this.setState({ data }));
}
2. Updation
Updating refers to the process of a component being
re-rendered due to changes in its state or props. This
phase occurs whenever a component’s internal state is
modified or its parent component passes new props.
When an update happens, React re-renders the
component to reflect the changes and ensures that the
DOM is updated accordingly.
getDerivedStateFromProps
setState() Function
shouldComponentUpdate()
getSnapshotBeforeUpdate() Method
componentDidUpdate()
getDerivedStateFromProps:-
getDerivedStateFromProps(props, state) is a static
method that is called just before the render() method
in both the mounting and updating phase in React. It
takes updated props and the current state as
arguments.
static getDerivedStateFromProps(props, state) {
if (props.name !== state.name) {
return { name: props.name };
}
return null;
}
setState():-
This is not particularly a Lifecycle function and can be
invoked explicitly at any instant. This function is used to
update the state of a component. You may refer to this
article for detailed information.
this.setState((prevState, props) => ({
counter: prevState.count + props.diff
}));
shouldComponentUpdate():-
shouldComponentUpdate() Is a lifecycle method in
React class components that determines whether a
component should re-render. It compares the current
and next props/states and returns true if the
component should update or false if it should not.
shouldComponentUpdate(nextProps, nextState)
It returns true or false, if false, then
render(), componentWillUpdate(), and componentDid
Update() method does not get invoked.
getSnapshotBeforeUpdate():-
The getSnapshotBeforeUpdate() method is invoked just
before the DOM is being rendered. It is used to store
the previous values of the state after the DOM is
updated.
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate():-
Similarly, this function is invoked after the component
is rendered, i.e., this function gets invoked once after
the render() function is executed after the updation of
State or Props.
componentDidUpdate(prevProps, prevState, snapshot)
3. Unmounting
This is the final phase of the lifecycle of the
component, which is the phase of unmounting the
component from the DOM. The following function is
the sole member of this phase.
componentWillUnmount():-
This function is invoked before the component is finally
unmounted from the DOM, i.e., this function gets
invoked once before the component is removed from
the page, and this denotes the end of the lifecycle.
Implementing the Component Lifecycle methods
Let us now see one final example to finish the article
while revising what’s discussed above.
First, create a react app and edit your index.js file from
the src folder.
// Filename - src/index.js:
import React from "react";
import ReactDOM from 'react-dom';
class Test extends React.Component {
constructor(props) {
super(props);
this.state = { hello: "World!" };
}
componentDidMount() {
console.log("componentDidMount()");
}
changeState() {
this.setState({ hello: "how are you!" });
}
render() {
return (
<div>
<h1>
Hai , Hello
{this.state.hello}
</h1>
<h2>
<a
onClick={this.changeState.bind(
this
)}
>
Press Here!
</a>
</h2>
</div>
);
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
return true;
}
componentDidUpdate() {
console.log("componentDidUpdate()");
}
}
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(<Test />);
// Filename - App.js
return (
<div>
<h2>ReactJs Form</h2>
<form>
<label>
Input Field:-
<input
value={value}
onChange={(e) => {
setValue(e.value);
}}
/>
</label>
</form>
</div>
);
}
Integrating third party libraries
Integrating React JS with other libraries is a common practice
in web development to utilize the functionality of those
libraries. React JS is itself a JavaScript library. ReactJS
workflow is like first importing the thing or component and
then using it in your code, you can export your components
and import wherever you like in your files. There are so many
ReactJS libraries or JavaScript libraries available like uuid,
toastify, etc. They can be easily integrated into your ReactJS
app.import React from 'react';
// Filename - App.js
Routing in react
React Router is a standard library for creating dynamic
routes and navigation in React JS Applications. It allows
you to manage navigation in your app by defining
routes that connect the URL paths to specific
components.
With React Router, you can implement different views
for different parts of your application without the need
for a full-page refresh. This is a key feature of single-
page applications (SPAs), where only the necessary
content is updated as the user navigates.
Types of React Routers:-
There are three types of routers in React:
1. BrowserRouter: The BrowserRouter is the most
commonly used router for modern React
applications. It uses the HTML5 History API to
manage routing, which allows the URL to be
dynamically updated while ensuring the browser’s
address bar and history are in sync.
2. HashRouter: The HashRouter is useful when you
want to use a URL hash (#) for routing, rather than
the HTML5 history API. It doesn’t require server
configuration and works even if the server doesn’t
support URL rewriting.
3. MemoryRouter: The MemoryRouter is used in
non-browser environments, such as in React
Native or when running tests.
Components of React Router:-
Here are the main components used in React Router:
1. BrowserRouter and HashRouter
BrowserRouter: Uses the HTML5 history API to
keep your UI in sync with the URL.
HashRouter: Uses the hash portion of the URL (i.e.,
window.location.hash) to keep your UI in sync with
the URL.
<BrowserRouter>
(/* Your routes go here */}
</BrowserRouter>
2. Routes and Route
Routes: A container for all your route definitions.
Route: Defines a single route with a path and the
component to render.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
3. Link and NavLink
Link: Creates navigational links in your application.
NavLink: Similar to Link but provides additional
styling attributes when the link is active.
<nav>
<NavLink to="/"
activeClassName="active">Home</NavLink>
<Link to="/about">About</Link>
</nav>
Example program:-
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link }
from 'react-router-dom';
function Home() {
return <h2>Home Page</h2>;
}
function About() {
return <h2>About Page</h2>;
}
function Contact() {
return <h2>Contact Page</h2>;
}
function App() {
return (
<Router>
<nav>
<Link to="/">Home</Link> |{" "}
<Link to="/about">About</Link> |{" "}
<Link to="/contact">Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
export default App;