0% found this document useful (0 votes)
26 views38 pages

Unit-3 FSD

This document provides an overview of React JS, including its features, history, and installation process. It covers key concepts such as React Router, Single Page Applications (SPAs), forms in React, and state management using Redux. Additionally, it includes examples and code snippets to illustrate the implementation of these concepts.

Uploaded by

hazira0534
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)
26 views38 pages

Unit-3 FSD

This document provides an overview of React JS, including its features, history, and installation process. It covers key concepts such as React Router, Single Page Applications (SPAs), forms in React, and state management using Redux. Additionally, it includes examples and code snippets to illustrate the implementation of these concepts.

Uploaded by

hazira0534
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/ 38

Unit - III

REACT JS
React JS
▪ Introduction to React Router
▪ Single Page Applications
▪ React Forms
▪ Flow Architecture
▪ Introduction to Redux
▪ More Redux
▪ Client Server Communication
React JS
▪ ReactJS is a declarative, efficient, and
flexible JavaScript library for building user
interfaces.

▪ It is an open-source, component-based
front-end library that is responsible only
for the view layer of the application.

▪ ReactJS is not a framework, it is just a


library developed by Facebook
React JS
History of ReactJS
• While building client-side application, a team of Facebook
developers found that DOM is slow.

• Document Object Model (DOM) is an application


programming interface(API) for HTML and XML
documents.

• It defines the logical structure of documents and how a


document is accessed and manipulated).

• To make it faster, React implements a virtual DOM which is


basically a DOM tree representation in JavaScript, and React
was invented.
React JS
History of ReactJS

• ReactJS is updated so frequently, that it is quite difficult to


navigate the version, which comes with new features every
time, each time it comes with new features.

• The current stable version of ReactJS is 18.2.0 and released


on June 14, 2022 and the first release was on May 29, 2013.
React JS
React Features:

▪ Use JSX

▪ Virtual DOM

▪ One-way Data Binding

▪ Component

▪ Performance
React JS
How does ReactJS work?
• React creates a virtual DOM in memory to update the
browser’s DOM. The virtual DOM will try to find the most
efficient way to update the browser’s DOM.
React JS
ReactJS Environment Setup
Pre-requisite: We must have NodeJS installed on our PC. So, the very first
step will be to install NodeJS. Once we have set up NodeJS on our PC, the
next thing we need to do is set up React

Installation of Node.js on Windows


Step-1: Downloading the Node.js ‘.msi’ installer
https://nodejs.org/en/download/
Step-2: Running the Node.js installer

Step-3: Select “Next”

Step-4: Select “Install”

Step-5: Click “Finish”

Step 6: Verify that Node.js was properly installed or not.


C:\Users\Admin> node –v

Step 7: Updating the Local npm version.


npm install npm –global // Updates the ‘CLI’ client
React JS
ReactJS Installation:
▪ Using create-react-app(faster method)
▪ Using webpack and babel

Method 1: Using create-react-app


Step 1: Navigate to the folder where you want to create the project
and open it in terminal

Step 2: In the terminal of the application directory type the following


command
npx create-react-app <<Application_Name>>

Step 3: Navigate to the newly created folder using the command


cd <<Application_Name>>

Step 4: A default application will be created with the following


project structure and dependencies
React JS
Step 5: To run this application
type the following command in
terminal
npm start
Step 6: The following output will
be displayed in the browser
React in HTML
• The quickest way start learning React is to
write React directly in your HTML files.

Hello World Example

• React renders HTML to the web page by using


a function called createRoot() and its
method render().
React in HTML
createRoot():-
• The createRoot() function takes one argument, an
HTML element.
• The purpose of the function is to define the HTML
element where a React component should be
displayed.

Render():-
• The render() method is then called to define the React
component that should be rendered.
But render where?
• There is another folder in the root directory of your
React project, named "public". In this folder, there is
an index.html file.
React in HTML
The Root Node
• The root node is the HTML element where you want to
display the result.
• It is like a container for content managed by React.
• It does not have be a <div> element and does not have to have
the id=‘root’
React using create-react-app
Example:-
/* Hello World*/
Step 1: npx create-react-app HelloWorld

Step 2: cd HelloWorld

Step 3: npm start


Cont…
Example - 1

Example program with create-react-app environment

import React from 'react';


import ReactDOM from 'react-dom/client';

const myFirstElement = <h1>Hello React!</h1>

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(myFirstElement);
Example - 1

Example program with create-react-app environment

import React from 'react';


import ReactDOM from 'react-dom/client';

function Car() {
return (
<h1>Hi, I'm a Car</h1>
);
}

const root=ReactDOM.createRoot(document.getElementById('root'));

root.render(<Car />);
Example - 1
Example program with create-react-app environment

import React from 'react';


import ReactDOM from 'react-dom/client';

function Car() {
return (
<h1>Hi, I'm a Car</h1>
);
}

function Vehicle() {
return (
<div>
<h1>What type of vehicle is this!</h1>
<Car/>
</div>
);
}

const root=ReactDOM.createRoot(document.getElementById('root'));

root.render(<Vehicle />);
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.

❖ You are not required to use JSX, but JSX makes it easier to
write React applications.

❖ Here are two examples. The first uses JSX and the second does
not:
What is JSX?

JSX:
const myElement = <h1>I Love JSX!</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);

Without JSX:
const myElement = React.createElement('h1', {}, 'I do not use JSX!’);

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(myElement);
1. React Router

React Router is a standard library for routing in React.

It enables the navigation among views of various components in a


React Application, allows changing the browser URL, and keeps the
UI in sync with the URL.

Routing is a critical component of the emerging single page


application (SPA), defining what should appear when a user accesses
a certain page in the application.

When a user clicks an element (link, button, icon, picture, etc.) or


enters a URL inside the application, routing allows them to travel
between different pages of the application.
import React, { Component } from "react";
import { BrowserRouter as Router, Routes, Route,
React Router
Link, } from "react-router-dom";
import Home from "./component/home"; <Routes>
import About from "./component/about"; <Route exact path="/“ element={<Home
import Contact from "./component/contact"; />}>
import "./App.css"; </Route>
<Route exact path="/about“
element={<About />}>
class App extends Component { </Route>
render() { <Route exact path="/contact"
return ( element={<Contact />}>
<Router> </Route>
<div className="App"> </Routes>
<ul className="App-header"> </div>
<li> </Router>
<Link to="/">Home</Link> );
</li> }
<li> }
<Link to="/about">
About Us
</Link> export default App;
</li>
<li>
<Link to="/contact">
Contact Us
</Link>
</li>
2. Single Page Applications
• A Single Page Application (SPA) is a web application that is designed to be
displayed as a single, static page.

• This approach makes the application more user-friendly and easier to navigate, as
users can see the entire application at once.

• With a traditional web application, users are redirected to a new page every time
they make a change to their data, which can be frustrating if they want to edit
information in multiple places.

• In contrast, SPA-based applications are completely focused on one thing at a time,


allowing users to work through each step in a consistent manner.
Single Page Applications

Advantages of SPAs
• A single page application has several advantages over traditional web
applications. Here are some of the most notable:

• Simplicity: SPAs are easier to develop and maintain than traditional web
applications. Developers only need to build a single HTML file for the
SPA. No server-side changes are necessary.

• Reusability: You can reuse the same JavaScript, CSS, and HTML code for
multiple pages, and there are tools that allow developers to package these
components into reusable modules.

• Security: SPAs make it easier to secure web pages, because they can be
protected by a firewall or require login credentials.

URL:- What Is a Single Page Application? | Bloomreach


import React from "react" import React from "react";
import { render } from "react-dom" import { useParams } from "react-router-dom";
import { BrowserRouter } from "react- export default function UserPage() {
router-dom" let { id } = useParams();
import App from "./App" return (
render( <>
<BrowserRouter> <h1>Hello there user {id}</h1>
<App /> <p>This is your awesome User Profile
</BrowserRouter>, page</p>
document.querySelector("#root") </>
) );
--------------------------------------------------------------
}
import React from "react"; ------------------------------------------------------
export default function HomePage() { import React from "react"
return ( import { Route, Switch } from "react-router-dom"
<> // We will create these two pages in a moment
import HomePage from "./pages/HomePage"
<h1>Hey from HomePage</h1> import UserPage from "./pages/UserPage"
<p>This is your awesome HomePage export default function App() {
subtitle</p> return (
</> <Switch>
); <Route exact path="/" component={HomePage} />
} <Route path="/:id" component={UserPage} />
</Switch>
)
}
import React from "react"
import { Link } from "react-router-dom"
export default function HomePage() {
return (
<div className="container">
<h1>Home </h1>
<p>
<Link to="/your desired link">Your desired link.</Link>
</p>
</div>
)
}
3. React Form
Example 1:-
import {useState} from 'react';

export default function ControlledComponent() {


const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {


setInputValue(event.target.value);
};

return (
<form>
<label>Input Value:
<input type="text" value={inputValue} onChange={handleChange}
/>
</label>
<p>Input Value: {inputValue}</p>
</div>
)};
Output
React Form
Example 2:-
import { useState } from "react";

export default function Dropdown() {


const [selectedOption, setSelectedOption] = useState("option1");

const handleDropdownChange = (event) => {


setSelectedOption(event.target.value);
};

return (
<div>
<label>
Select an option: <select value={selectedOption} onChange={handleDropdownChange}>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</label>
<p>Selected option: {selectedOption}</p>
</div>
);
}

Output
4. Redux

What is Redux?
• Redux is a state management library that allows you to
manage the state of your JavaScript applications more
efficiently and predictably.

• Instead of passing this information from component to


component using props, Redux allows you to store them in one
central location where they can be easily accessed and
updated. This makes it easier to manage complex states and
keep your application organized.
Redux

What is state in React?


• In modern React, we build our applications with functional
components. Components are themselves JavaScript functions,
independent and reusable bits of code.

• The state is an object that holds information about a certain


component.

• Plain JavaScript functions don't have the ability to store information.


The code within them executes and "dissapears" once the execution is
finished.

• But thanks to state, React functional components can store


information even after execution. When we need a component to store
or "remember" something, or to act in a different way depending on
the environment, state is what we need to make it work this way.
Redux

Why use React Redux?


The main reason to use React Redux are:
• React Redux is the official UI bindings for react Application. It is kept up-
to-date with any API changes to ensure that your React components behave
as expected.
• It encourages good 'React' architecture.
• It implements many performance optimizations internally, which allows to
components re-render only when it actually needs.
Redux

The components of Redux architecture are explained below.


• STORE: A Store is a place where the entire state of your application lists.
It manages the status of the application and has a dispatch(action) function.
It is like a brain responsible for all moving parts in Redux.

• ACTION: Action is sent or dispatched from the view which are payloads
that can be read by Reducers. It is a pure object created to store the
information of the user's event. It includes information such as type of
action, time of occurrence, location of occurrence, its coordinates, and
which state it aims to change.

• REDUCER: Reducer read the payloads from the actions and then updates
the store via the state accordingly. It is a pure function to return a new state
from the initial state.
Redux
Example:-
At src/app/store.js create the following:
import { configureStore } from '@reduxjs/toolkit’

export default configureSTore({


reducer: {}
})

Then, head to index.js and wrap your App component like so:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import store from './app/store'


import { Provider } from 'react-redux'

ReactDOM.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>,
document.getElementById('root')
);
Redux
Counter Component
For this example, we will be creating a simple counter.
When using a Class component, you would see something like this:
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrementCounter, incrementCounter } from './counterSlice'

export function Counter() {


const count = useSelector((state) => state.counter)
const user = useSelector((state) => state.user)

const dispatch = useDispatch()

return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(incrementCounter())}
>
Increment
</button>
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrementCounter())}
>
Decrement
</button>
</div>
</div>
)
}

export default connect(mapStateToProps, mapDispatchToProps)(Counter)


5. Client Server Communication
Let's expand the application so that the notes are stored in the backend. We'll use json-
server, familiar from part 2.

The initial state of the database is stored in the file db.json, which is placed in the root
of the

project:
{
"notes": [
{
"content": "the app state is in redux store",
"important": true,
"id": 1
},
{
"content": "state changes are made with actions",
"important": false,
"id": 2
}
]
}
Client Server Communication
We'll install json-server for the project...
npm install json-server --save-dev

and add the following line to the scripts part of the file package.json

"scripts": {
"server": "json-server -p3001 --watch db.json",
// ...
}

Now let's launch json-server with the command npm run server.
Next, we'll create a method into the file services/notes.js, which uses axios to fetch data from the
backend

import axios from 'axios’


constbaseUrl = 'http://localhost:3001/notes’
constgetAll = async () => {
const response = await axios.get(baseUrl)
return response.data
}
export default { getAll }

We'll add axios to the project


npm install axios
Client Server Communication
We'll change the initialization of the state in note Reducer, so that by default there are no
notes:
constnoteSlice = createSlice({
name: 'notes’,
initialState: [], // ...
})
The code communicating with the server as follows:
constbaseUrl = 'http://localhost:3001/notes’
constgetAll = async () => {
const response = await axios.get(baseUrl)
return response.data
}
constcreateNew = async (content) =>
{ const object = { content, important: false } const response = await
axios.post(baseUrl, object) return response.data}
export default {
getAll,
createNew,
}
Client Server Communication
The method addNote of the component NewNote changes slightly:
import { useDispatch } from 'react-redux'
import { createNote } from '../reducers/noteReducer'
import noteService from '../services/notes'
constNewNote = (props) => {
const dispatch = useDispatch()
constaddNote = async (event) =>{ event.preventDefault()
const content = event.target.note.value
event.target.note.value = ''
constnewNote = await noteService.createNew(content) dispatch(createNote(newNote)) }
return (
<form onSubmit={addNote}>
<input name="note" />
<button type="submit">add</button>
</form>
)
}
export default NewNote
Because the backend generates ids for the notes, we'll change the action creator createNot
accordingly:
createNote(state, action) {
state.push(action.payload)
}

You might also like