0% found this document useful (0 votes)
13 views

React Js Unit-I Done

ReactJS is a flexible and efficient JavaScript library for building reusable UI components, created by Facebook. It supports various development scopes including web and mobile applications, server-side rendering, and progressive web apps, while also being backed by a large community. The document outlines the advantages and disadvantages of ReactJS, its component structure, and the differences between JavaScript and JSX.

Uploaded by

Akash Kale
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)
13 views

React Js Unit-I Done

ReactJS is a flexible and efficient JavaScript library for building reusable UI components, created by Facebook. It supports various development scopes including web and mobile applications, server-side rendering, and progressive web apps, while also being backed by a large community. The document outlines the advantages and disadvantages of ReactJS, its component structure, and the differences between JavaScript and JSX.

Uploaded by

Akash Kale
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/ 26

Unit 1: Introduction to ReactJS

Introduction

● ReactJS is a declarative,efficient, and flexible javascript library for building


reusable UI Components.
● It is an open-source,component-based front end library responsible only for the
view layer of the application.
● It was created by jordan walke,who was a software engineer at facebook.
● It gives the developers much more freedom than angular or vue.
● ReactJs, also known as React,is a popular javascript library for building user
interfaces.
● It was developed by facebook and is widely used for creating dynamic and
interactive web applications.
● React is fast and works well with other tools and libraries.
● React is a tool for building UI components.

Workflow

Following the steps for workflow of reactJS

● Install Node.js and npm


● Create a New React Application
○ npx create-react-app my-app
○ cd my-app
● Understand the generated structure (public, src, etc.).
● Start Development Server
○ npm start
● Edit files in the src folder, particularly App.js.
● Create new components in the src folder.
● Use React hooks (useState, useEffect) or state management libraries like Redux.
● Use CSS, SASS, or styled-components for styling.
● Use React Router for navigation:
○ npm install react-router-dom
● Use fetch or Axios for API calls.

Scope

1. Web Development

a. Single Page Applications (SPAs)

ReactJS is ideal for building SPAs where the application loads a single HTML page and
dynamically updates as the user interacts with the app.

b. Interactive User Interfaces

ReactJS allows developers to create highly interactive UIs with real-time updates and a
responsive user experience.

c. Component-Based Architecture

React's component-based architecture promotes reusability and modularity, making it


easier to manage and scale large applications.

2. Mobile Development

a. React Native

ReactJS can be used to develop mobile applications through React Native, allowing
developers to build native apps for iOS and Android using the same React codebase.

3. Server-Side Rendering (SSR)

a. Next.js
Frameworks like Next.js leverage ReactJS for SSR, improving performance and SEO
by rendering pages on the server before sending them to the client.

4. Progressive Web Apps (PWAs)

ReactJS is used to build PWAs, which offer a native app-like experience on the web
with features like offline access, push notifications, and fast load times.

5. Static Site Generation (SSG)

a. Gatsby

React-based frameworks like Gatsby enable developers to build static websites that are
fast, secure, and can be easily integrated with various data sources.

6. Enterprise Applications

ReactJS is widely adopted in enterprise environments for building scalable and


maintainable web applications with complex user interfaces.

7. E-commerce Platforms

ReactJS is used to create dynamic and responsive e-commerce websites, offering a


seamless shopping experience to users.

8. Cross-Platform Development

ReactJS, along with tools like Electron, can be used to build cross-platform desktop
applications using web technologies.

9. Community and Ecosystem

ReactJS has a large and active community, contributing to a rich ecosystem of libraries,
tools, and resources that enhance development productivity.

10. Job Market and Demand


ReactJS developers are in high demand, with numerous job opportunities in startups,
tech giants, and enterprises due to the popularity and widespread adoption of ReactJS
in the industry.

The versatility and robust features of ReactJS make it a powerful tool for a wide range
of development projects, from simple websites to complex, large-scale applications.

Pros and Cons (advantages and disadvantages)

Advantages of ReactJS

Following are the main advantages of ReactJS −

● Performance
● Easy to learn
● Huge collection of third party components
● Large community
● SEO Friendliness
● Easy kick-starting of the React project
● Rich set of developer tools
● Handle large application
● Simple UI testing

1. Performance

React uses Virtual DOM concept to check and update the HTML document. Virtual
DOM is a special DOM created by React. Virtual DOM represents the real DOM of the
current document. Whenever there is a change in the document, React checks the
updated virtual DOM with the previous state of the Virtual DOM and update only the
different in th actual / real DOM. This improves the performance of the rendering of the
HTML document.
For example, if we create a React component to show the current time by periodically
updating the time through setInterval() method, then React will update only the current
time instead of updating the whole content of the component.

2. Easy to learn and use

ReactJS is much easier to learn and use. It comes with a good supply of
documentation, tutorials, and training resources. Any developer who comes from a
JavaScript background can easily understand and start creating web apps using React
in a few days. It is the V(view part) in the MVC (Model-View-Controller) model, and
referred to as ?one of the JavaScript frameworks.? It is not fully featured but has the
advantage of open-source JavaScript User Interface(UI) library, which helps to execute
the task in a better manner.

3. Huge collection of third party components

In addition to the core React library (which is only a few KB in size), React community
provides a large number of components for a wide range of applications from simple UI
components to full-fledged PDF Viewer components. React provides multiple options in
each category. For example, the advanced state management can be done using either
Redux or MobX library. Redux and Mobx are just two popular libraries to do state
management. React has more than 10 libraries to archive the same functionality.
Similarly, React community provides lot of third party library in each category like
routing, data grid, calendar, form programming, etc.,

4. Large community

The React developer community is a huge community with a lot of activities. React
community is very active that you can get answer for any react related question / doubts
in a few minutes through google, stackoverflow, etc.,

5. SEO friendliness
React is one of the few JavaScript library to support SEO features. Since React
components and JSX are similar to HTML elements, SEO can be easily achieved
without much code / setup.

6. Easy kick start of React project

React provides a CLI application, create-react-app to create a new react application.


create-react-app application not only creates a new application, it also builds and runs
the application in the local environment without any other dependencies.
create-react-app allows the developer to choose a template, which allows the
application to include more boilerplate code during initial setup itself. This allows the
developer to kickstart a small application to a large application in a few clicks.

In addition to create-react-app, React community additional tools such as nextjs, gatsby,


etc., which allows developers to create advanced applications in a short period of time.

7. Rich set of developer tools

React community provides essential developer tools to enhance the developer


productivity. React developer tool for chrome, edge and firefox browser enables
developer to select a react component and see the current state of the component.
Also, it enables the developer to have a clear picture of the view of the component
hierarchy by showing it as a tree of components in the Developer Tab of the browser.

8. Handle large application

React uses composition to merge multiple components into one bigger component,
which in turn allows it to create a much larger component. React components can be
created in a single JavaScript file and can be set as exportable. This feature allows
multiple components to be grouped under a common category as modules and can be
reused in other places.
Composable and modular features of the React library allows developer to create large
applications, which is relatively easy to maintain when compared to other front end
frameworks.

Disadvantages of React

● Lack of quality documentation


● No standard / recommended way to develop application
● Fast development pace
● Advanced use of JavaScript
● JavaScript extension
● Just a UI library

1. Lack of quality documentation

React library has a decent documentation in its primary website. It covers the basic
concept with few examples. Even though, it is a good start to understand the basic of
React concept, it does not provides a deep and detailed explanation with multiple
examples. React community steps in and provides lot of articles with varying level of
complexity and quality. But, they are not organized under one place, where the
developer can easily learn.

2. No or Less standard way to develop application

React is just a UI library with few concept and standard recommendation. Even through
React can be use to create large / complex application, there is no standard or
recommended way to create a application. As there is no standard way, React
community uses multiple architecture to build their application. Developer are free to
choose a methodology for their application. A wrong choice at the beginning of the
application development complicates the application as well as delay the development
of the application.

3. Fast development pace

React releases new version of the library few times in a year. Each release has few
addition feature and few breaking changes. Developer need to learn fast and apply the
new concept to stabilize the application.

4. Advanced use of JavaScript

Even through the core concept of the React library is quite simple and easy to learn, the
advanced concept are quite complex as it exploits advanced features of JavaScript.
Also, React has lot of advanced concept to address many of the complex scenarios of
the HTML / Form programming. The shear number of advanced concept is really quite a
challenge for the developer to learn and master it.

5. JavaScript Extension

JSX is an extension of JavaScript language. JSX is similar to HTML and simplifies the
component development. JSX also has few differences with the HTML Programming
and need to be careful to apply it correctly. Additionally, JSX needs to be complied to
JavaScript before executed in the browser which is addition step / burden for the
application.

6. Just a UI library

As we learned earlier, React is just a UI library and not a framework. Creating a React
application with good architecture needs careful selection and application of additional
third party react library. A bad design may affect the application in the later / final stage
of the application development.
Difference between JS and JSX

What is JS?

JavaScript (JS) is a programming language commonly used for developing web


applications. It is a versatile and dynamically-typed language that runs on the client-side
(in web browsers) and server-side (with the help of platforms like Node.js). JavaScript
enables interactive and dynamic functionality on web pages, allowing developers to
manipulate and modify content, handle user interactions, and communicate with
servers.

What is JSX?

JSX, on the other hand, stands for JavaScript XML. It is an extension to JavaScript
syntax that allows you to write HTML-like code within JavaScript. JSX is commonly
used in conjunction with React, a popular JavaScript library for building user interfaces.
JSX provides a more declarative and intuitive way to define the structure and
appearance of components, making it easier to develop and maintain complex UIs. JSX
code is transpiled into regular JavaScript code before it can be executed in the browser.

The notable difference between a .js file and .jsx is that in a .js file, you’re writing
JavaScript and in .jsx file, you’re writing JSX. Of course, you can still write JSX inside a
.js file, but having a separate file for JSX and vanilla JavaScript would reduce
confusion in a large React codebase.

Another difference between a .js and .jsx file is that code editors and their themes
might have different syntax highlighting for JavaScript and JSX. Once you separate the
two in your codebase, things could become easier for you visually.

.js: Used for general JavaScript code.


.jsx: Used with React or similar UI libraries, adding an HTML-like syntax to
JavaScript.

1. .js Files:

● Files containing JavaScript code have the .js extension.

● You can use all the core functionalities of JavaScript in these files, like

variables, functions, loops, and conditionals.

● They cannot directly interact with HTML.

2. .jsx Files:

● .jsx files also contain JavaScript code, but with the added ability to use an

HTML-like syntax.

● This allows you to integrate your JavaScript code directly with HTML

elements.

● They are used by UI libraries like React, AngularJS, and Vue.js.

React Components overview

● Components are independent and reusable bits of code. They serve the same

purpose as JavaScript functions, but work in isolation and return HTML.


● Components come in two types, Class components and Function components, in

this tutorial we will concentrate on Function components.

● A React component represents a small chunk of user interface in a webpage.

The primary job of a React component is to render its user interface and update it

whenever its internal state is changed. In addition to rendering the UI, it manages

the events belongs to its user interface. To summarize, React component

provides below functionalities.

● Initial rendering of the user interface.

● Management and handling of events.

● Updating the user interface whenever the internal state is changed.

React component accomplish these feature using three concepts −

​ Properties − Enables the component to receive input.

​ Events − Enable the component to manage DOM events and end-user

interaction.

​ State − Enable the component to stay stateful. Stateful component updates its UI

with respect to its state.

There are two types of components in React. They are −

​ Function Components

​ Class Components


Class Component

A class component must include the extends React.Component statement. This

statement creates an inheritance to React.Component, and gives your component

access to React.Component's functions. The component also requires a render()

method, this method returns HTML.

Example

Create a Class component called Car

class Car extends React.Component {

render() {

return <h2>Hi, I am a Car!</h2>}}

Function Components

A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier
to understand, and will be preferred in this tutorial.

Example

function Car() {

return <h2>Hi, I am a Car!</h2>;

}
Child Components

Child components in ReactJS are components that are nested within parent
components. They are used to build modular and reusable pieces of UI. Here are some
key points about child components in ReactJS:

1. Reusability: Child components can be reused across different parts of the


application, promoting DRY (Don't Repeat Yourself) principles.
2. Separation of Concerns: By breaking down the UI into smaller, manageable
pieces, child components help in maintaining a clean and organized codebase.
3. Props for Data Flow: Parent components pass data to child components via
props. This enables a unidirectional data flow which is easier to understand and
debug.
4. State Management: Child components can manage their own state. However,
for complex state management, it’s often better to lift the state up to the parent
component or use state management libraries like Redux.
5. Lifecycle Methods: Child components have their own lifecycle methods (e.g.,
componentDidMount, componentDidUpdate) which can be used to perform
actions at specific points in the component's lifecycle.
6. Event Handling: Child components can handle their own events (e.g., onClick,
onChange). Parent components can also pass event handlers as props to child
components.
7. Composition: Child components can be composed to form complex UIs. This
composition makes it easier to build scalable and maintainable applications.
8. Context API: For passing data deeply through the component tree without
having to pass props at every level, the Context API can be used. This is
particularly useful for global data like theme, user information, etc.
9. Refs: Parent components can create refs and pass them to child components to
directly interact with the DOM elements or child component instances.
10. Prop Types: Defining prop types for child components helps in validating the
data types of props being passed and makes the components more robust and
easier to debug.
JSX expressions

● Expressions in JSX are javascript expressions that can be used to evaluate and
display dynamic values within JSX code.
● They are defined within curly braces({}).
● These expressions can be any valid javascript expressions,including
variables,function calls and operations.

Building Blocks of ReactJS:

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.
● JSX helps us keep our code simpler and elegant when writing large pieces of
code.
● JSX also allows React to show more useful error and warning messages.
● JSX converts HTML tags into react elements.

Example

import React from 'react';

import ReactDOM from 'react-dom/client';

const myElement = <h1>I Love JSX!</h1>;

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

root.render(myElement);
Components
● Components are like functions that return HTML elements.
● Components are independent and reusable bits of code.
● They serve the same purpose as JavaScript functions, but work in
isolation and return HTML.
● Components come in two types,
○ Class components
○ Function components
● Components in React serve as independent and reusable code blocks for UI
elements.
● They represent different parts of a web page and contain both structure and
behavior.
● They are similar to JavaScript functions and make creating and managing
complex user interfaces easier by breaking them down into smaller, reusable
pieces.
● A UI is broken down into multiple individual pieces called components.

State and Props

1.Props
● props are a way to pass the data or properties from parent component to
child components.
● Props are read-only components.
● It is an object which stores the value of attributes of a tag and work similar
to the HTML attributes.
● It allows passing data from one component to other components.
● It is similar to function arguments and can be passed to the component
the same way as arguments passed in a function.
● Props are immutable so we cannot modify the props from inside the
component.
2.State
● state is the real-time data available to use within that only component.
● The state is an updatable structure that is used to contain data or
information about the component and can change over time.
● The change in state can happen as a response to user action or system
events.
● It is the heart of the react component which determines the behavior of
the component and how it will render.
● A state must be kept as simple as possible.
● It represents the component's local state or information.
● It can only be accessed or modified inside the component or by the
component directly.

Difference between State and Props

sr.no Props State

1. Props are read-only. State changes can be asynchronous.

2. Props are immutable. State is mutable.

3. Props allow you to pass data from one State holds information about the

component to other components as an components.

argument.

4. Props can be accessed by the child State cannot be accessed by child

component. components.
5. Props are used to communicate between States can be used for rendering dynamic

components. changes with the component.

6. Stateless component can have Props. Stateless components cannot have State.

7. Props make components reusable. State cannot make components reusable.

8. Props are external and controlled by The State is internal and controlled by the

whatever renders the component. React Component itself.

Conditional Rendering

● Conditional rendering in React works the same way conditions work in


JavaScript.
● Use JavaScript operators like if or the conditional operator to create elements
representing the current state, and let React update the UI to match them.
● Conditional rendering in React refers to the process of delivering elements and
components based on certain conditions.
● Conditional rendering in React can be implemented in three ways: Using if else
Statement. Using Logical && Operator. Using ternary operator.

Example

Consider these two components:


function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}

We’ll create a Greeting component that displays either of these components

depending on whether a user is logged in:


function Greeting(props) {
const isLoggedIn = props.isLoggedIn;

if(isLoggedIn)
{
return <UserGreeting/>;
}
return <GuestGreeting/>;

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

// Try changing to isLoggedIn={true}:

root.render(<Greeting isLoggedIn={false}/>);

Advantages of JSX

● JSX enables React to display error and warning messages, which aids in
debugging.
● With JSX, you can write large pieces of code in a more organized and simplified
manner.
● If you have a good understanding of HTML, you'll find it easier to use JSX when
developing React applications.
● It is easy to write HTML text in React using JSX.
● HTML tags can easily be converted to React JS elements.
● The programming language becomes faster than when you use JavaScript.
● You can put HTML elements in DOM without using appendChild() or
createElement().
● XSS (cross-site-scripting) attacks, also known as injection attacks, can be
prevented with the use of JSX.
● You can detect most of the errors during the compilation time only.
● Being an expression, JSX can be used inside ‘if statements’ and ‘for loops’. It is
also possible to assign this expression to variables and accept it as arguments.

Expressions in JSX

● Expressions in JSX are JavaScript expressions that can be used to evaluate and
display dynamic values within JSX code.
● They are defined within curly braces ({}).
● These expressions can be any valid JavaScript expressions, including variables,
function calls, and operations.
● Any statement that can return a value is automatically qualified to be used as an
expression.
● An expression is a combination of values, variables, and operators, which
computes to a value.

Implementation of JSX

JSX (JavaScript XML) is a syntax extension for JavaScript used with React to describe
what the UI should look like. It resembles HTML but comes with the full power of
JavaScript.

1. Setting Up a React Project

First, ensure you have Node.js and npm installed. You can create a new React project
using Create React App:

npx create-react-app my-app


cd my-app
npm start

2. Creating a Component with JSX

Inside your project, you can create a new component using JSX. For example, create a
HelloWorld component.

src/components/HelloWorld.js

import React from 'react';

const HelloWorld = () => {


return (
<div>
<h1>Hello, World!</h1>
<p>This is a simple React component using JSX.</p>
</div>
);
};
export default HelloWorld;

3. Using the Component in Your App

You can now use the HelloWorld component in your main App.js file.

src/App.js
import React from 'react';
import HelloWorld from './components/HelloWorld';

function App() {
return (
<div className="App">
<header className="App-header">
<HelloWorld />
</header>
</div>
);
}

export default App;

4. Running Your App

Now, you can run your application using:

npm start

This will start the development server and open your app in a browser. You should see
"Hello, World!" displayed on the page.

Environment Setups

How to use NPM

1.Install NodeJS and NPM.NodeJS and NPM are the platforms need to develop any
ReactJS applications.
2. install React and React DOM.

3.install webpack

4.install babel

5.create files

6.configure webpack

7.webpack.config.json

8.HTML webpack template for index.html

NPM and setting Environment for ReactJs Projects

NPM is a package manager that can be used to set up a React.js.

Development environment along with Node.js and create React App.

● Install Node.js and npm


● Install Create React App
● Create a React project
● Explore the project structure
● Run the development server

Here are Some steps you can take to set up a React.Js development
environment.

● Open a command prompt or terminal


● Install Create React App globally: npm install -g create-react-app
● Create a project: npx create-react-app my-first-react-app
● Navigate to your project folder: cd my-first-react-app
● Start the development server: npm start
● Open your web browser and go to http://localhost:3000
how to create package.json and purpose in reactjs

The easiest way to create a package. json file is to run npm init to
generate one for you.

IDE for ReactJS

Visual Studio Code, also known as VS Code, is a highly versatile and popular IDE
among React developers. It offers built-in support for JavaScript and React, an
extensive marketplace of plugins, and features such as code completion, React Router
integration, and debugging. It is available for Windows, Mac, and Linux.

Reactjs browser plugins overview

React. js development tools (React DevTools) is a browser plugin that allows


you to investigate the React component hierarchy in the Chrome developer
tools. It is available for Chrome, Firefox, and as a standalone app. This
extension extends the Chrome Developer Capabilities to provide React
debugging tools.

converting functional component to class component

To convert a function component to a class component we need to make


the following major changes.
● Change the function to a class.
● Add the render method.
● Convert all functions to a method.
● Add Constructor.
● Replace hooks with lifecycle methods.
Component life cycle and its different methods
The component life cycle in React has three phases, each with its own lifecycle method

● Mounting: When a component is first created and inserted into the DOM.
● Updating: When a component's state or props change.
● Unmounting: When a component is removed from the DOM.

1.Initialization:

The is the stage where the component is constructed with the given props and
default state.This is done in the constructor of a component class.

2.Mounting:

Mounting is the stage of rendering the JSX returned by the render method itself.

3.Updating:

Updating is the stage when the state of a component is updated and the
application is repainted.

4.unmounting:

As the name suggests unmounting is the final step of the component lifecycle
where the component is removed from the page.

You might also like