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

REACTJS(NOTES-PDF)

React JS is a powerful JavaScript library for building dynamic user interfaces, particularly for single-page applications, utilizing a component-based architecture and a virtual DOM for performance optimization. Developed by Jordan Walke at Facebook and open-sourced in 2013, React allows for reusable UI components and efficient state management. The document also covers installation methods, JSX syntax, component types, and the reconciliation process for updating the DOM.

Uploaded by

saitejareddy8542
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
87 views

REACTJS(NOTES-PDF)

React JS is a powerful JavaScript library for building dynamic user interfaces, particularly for single-page applications, utilizing a component-based architecture and a virtual DOM for performance optimization. Developed by Jordan Walke at Facebook and open-sourced in 2013, React allows for reusable UI components and efficient state management. The document also covers installation methods, JSX syntax, component types, and the reconciliation process for updating the DOM.

Uploaded by

saitejareddy8542
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 33
React Js:— - React Js is Javascript libraray — ReactJS, is a popular and powerful JavaScript library used for building dynamic and interactive user interfaces, primarily for single—page applications (SPAs). — It allows developers to create reusable Ul components and manage the state efficiently. — React is a JavaScript library for building user interfaces (UIs) on the web. — React is a declarative, component based library that allows developers to build reusable Ul components and It follows the Virtual DOM (Document Object Model) approach, which optimizes rendering performance by ing DOM updates, History of ReactJs: - Jordan Walke, a software engineer at Facebook, developed the first version of React, initially named FAXJS. - They made react js as open source in year 2013. Characteristics of ReactJS: 1.Component—Based Architecture: React applications are built using small, reusable components. Virtual DOM: React uses a virtual DOM to improve performance by direct manipulation of the real DOM. imizing 3.Declarative Syntax: React code is declarative, making it easier to read and debug. 4.Uni-directional data flow: Data flows in a single direction, enhancing control and predictability. 5.JSX GavaScript XML): JSX allows writing HTML-like syntax within JavaScript. 6.Write Once and use Anywhere. Advantages of ReactJS: ~ Fast Rendering: The virtual DOM ensures updates are efficient, reducing the load on the actual DOM. — Reusable Components: Promotes code reusability, reducing development time and effort in maintenance. ~ Rich Ecosystem: React provides various tools and libraries, such as React Router and Redux, for seamless development. — Strong Community Support: React has a large and active developer community, ensuring robust support and resources. Single page Application Vs Multipage Application: Single Page Application: Multipage Application 1. Having only one webpage 1. Having Multiple webpages 2, Requests are less. 2, Requests are More 3. Rendering time is very less 3. Rendering time is more 4, Example:Instagram, YouTube,Linkdin,FaceBook 4, Example: W3schools,Javatpoint,flipkart WHAT IS DOM: — DOM is the tree data structure used by the browser , and it is the representation of structured object in the form of tree structure, any updates in the dom results in re- rendering and repainting of the UI WHY React USES Virtual DOM: - The DOM (Document Object Model) in the browser is like a tree of all the elements on a web page. When you update something, the browser checks and reloads parts of this tree, which can slow down performance. React solves this by using a Virtual DOM. Virtual DOM: ~ The virtual DOM is a lightweight copy of the real DOM that allows React to manage changes more efficiently by minimizing the direct manipulation required on the real DOM — Virtual DOM is the clone of real DOM. - When the DOM is loaded than only you can get the data and store into virtual DOM , First time we have to capture the Real DOM and it is done by ReactDOM , Next time onwards it dont use real dom instead of that it use virtual DOM — No Re Rendering takes place in virtual DOM. Diffing Algorithm: — It compares the new virtual DOM with the previous one to identify the differences. — This comparison is done using a highly optimized diffing algorithm, which minimizes the number of DOM operations required to update the real DOM. Updating the Real DOM: — Once the diffing process identifies the necessary changes, React applies them to the real DOM in a batched manner. ~ This ensures that the browser only performs the minimum required updates, resulting in improved performance. Patching: — Once the diffing algorithm identifies the changes, React generates a set of patches — instructions for updating the real DOM. — These patches are applied in a batched manner, minimizing the number of DOM manipulations and improving performance Reconicilation process: — The process of comparing the previously created virtual DOM copy with the newly created virtual DOM copy using a diffing algorithm is known as the reconciliation process. Steps of reconcilation Process: ~ React stores a copy of Browser DOM which is called Virtual DOM. 1.When we make changes or add data, React creates a new Virtual DOM and compares it with the previous one. 2.Comparison is done by Diffing Algorithm. The cool fact is all these comparisons take place in the memory and nothing is yet changed in the Browser. 3.After comparing, React goes ahead and creates a new Virtual DOM having the changes. It is to be noted that many as 200,000 virtual DOM nodes can be produced in a second. 4.When the state of a component changes, React compares the VDOM of the last and current states and calculates the minimum number of DOM. operations required to update the actual DOM to match the current VDOM Babel: — Babel is a JavaScript compiler. - Babel is a compiler that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Installation 1. Installing React Using Create React App This is the easiest and most common way to set up a React project. Steps: L.Install Node.js: - Download and install Node.js from the official website. ~ Verify the installation: node —v mpm —Vv 2. Install create-react—app globally in your system. (only once) — npm install ~g create—react~app to install create-react-app — Run the following command in your terminal: — create—react—app my—app ~ Replace my~app with your desired project name. 3.Navigate to Your Project Directory: ed my-app 4.Start the Development Server: ~ npm start — Your app will open in the browser at http://localhost:3000/. Installing React Using npx Create React App: -This is one of the easiest and most common ways to set up a React project. Steps: 1.Install Node.js: — Download and install Node.js from the official website. ~ Verify the installation by running the following commands in your terminal: node npm —v Create a React Application: — Run the following command in your terminal: npx create-react: pp my—app — Replace my-app with your desired project name. — The npx command ensures you are using the latest version of Create React App without globally installing it. 3.Navigate to Your Project Directory: — ed my~app 4,Start the Development Server: — npm start — Your app will open automatically in the browser at http://localhost:3000/. Installing React Using Vit ~— Vite is a fast build tool and alternative to Create React App. Steps: Lnstall Node.js (if not already installed) 2.Create a React Application: — npm create vite@latest my-app 3.Select Framework and Language: — When prompted, select the framework as React. 4.Choose the desired variant: — JavaScript for plain JavaScript, — TypeScript for TypeScript support. 5.Navigate to Your Project Directory: — ed my—app 6.Install Dependencies: — npm install 7.Start the Development Server: — npm run dev — Your app will open in the browser at the URL provided by Vite. What is npm’? — Npm means node package manager , this command is only for installing packages , its not for executing packages — NPM stands for Node Package Manager, and it's a free, open-source tool that helps developers install, manage, and share JavaScript packages. What is npx? — Npx means node package extender/Excute , without installing packages you can execute applic: React Libraries 1.React — The "react" is a core library of react, ~ It contains functionalities to manage and maintain components, states and handling events. ~ import React from "react" 2.ReactDOM - The "react—dom" library is responsible for rendering the components into the Ul/into the DOM tree. ~ import ReactDOM from "react-dom/client" CreateRoot: ~ createRoot is a function in React that allows you to create a root for rendering React components within a specified DOM node. — This method files, s a bridge or connector between index.html and index.js ~ This method will show the path to React that where all the code has to render. = Import {createRoot} from react-dom/client library — Syntax, import {createRoot} from "react-dom/client"; createRoot (document.getElementByld (‘root")) render (

React 18 onwards use createRoot function ....

Or import ReactDOM from "react-dom/client"; ReactDOM.createRoot (document.getElementByld("root")).render ( React 18 onwards use createRoot function .... oF createElement: — The React.createElement method is used to create React elements programmatically. — It serves as an alternative to using JSX. ~ It takes three parameters: the element type (e.g., a string for a DOM tag or a function for a React component), an object containing the element's properties (props), and any child elements. ~ It returns a plain JavaScript object that represents a virtual DOM node. - Syntax of createElement React.createElement (clementtype, property / attribute, ... (children /content)); — Example: import {createElement)} from "react"; import ReactDOM from "react-dom/client"; let clement= createElement ("p", {className:"para"},"I am para from react app") createRoot (document.getElementByld ("root") .render (element) ~ If you want to render multiple elements created using the React.createElement method and pass them to the createRoot method, you typically wrap them inside a single container element. import React from ‘react’; import ReactDOM from 'react-dom/client'; // Create multiple elements const element] = React.createElement (‘h1', null, ‘Hello, React!"); const element2 = React.createElement(‘p’, null, "This is a simple example.’ // Wrap elements in a parent container createElement (‘div', null, element1, element2); const container = React // Render to the DOM const root = ReactDOM.createRoot (document.getElementByld (‘root’); root.render (container) ; ISX: - JSX, or JavaScript XML, is a syntax extension for JavaScript that allows users to write HTML-like markup inside a JavaScript file ~ It is the template language for reactjs — Jsx means javascript xml or javascript extension - Jsx allow us to combine html and js in react , basically it is a syntax allowing us to combine html and js in react easily = It looks similar to html but it is not html. — Without jsx it is very difficult to create react application ~ It is the advance version of javascript if you want to render it you need babel is, ~ Babel js is internally converts jsx to browser understandable javascript. Rules of JSX: 1 Rule: Close all tags: Explicitly close all tags, including self-closing tags like . 2.Rule2: In jsx we have to use camelCase convention 3.Rule3: Same level elements if you are having then you should wrap them in a parent element. ReactDOM.createRoot (document.getElementByld("root")).render (
Hello Hii
); 4.Ruled: Ins attribute in jsx and Instead of using for attribute of label , ead of using class as the attribute , you should use className as the we should have to use htmlFor here. Ex:
5.Rule5: If you want to use multiple lines of JSX than you should have to wrap them in parentheses , otherwise react will throw a warning. Ex : let list = (
  • Raj
  • Nikhil
  • Suraj
  • React Fragments: — React Fragment is a feature in React that allows you to return multiple elements from a React component by allowing you to group a list of children without adding extra nodes to the DOM. It won’ t add extra node to the DOM ~ It only accept key property , it will not accept any other properties ~ Syntax Ex: //? here in this case this extra node as div has been added to the DOM ReactDOM.createRoot (document. getElementByld ("root") render (
    //! adding extra node to the DOM
  • hello
  • world
  • and India
  • 3 // avoiding extra node from adding to the DOM import React from "react" import {Fragment} from "react" ReactDOM.createRoot (document.getElementByld (‘root")).render ( //! not adding extra node to the DOM
  • hello
  • world
  • and India
  • — shorthand Fragment component: ~ But here in this shorthand fragment There is a difference — You cannot add key property Ex: <>
  • one
  • two
  • three
  • Components: — React components are the core building block of the any react application. — Components are nothing but a block of code, we have to export and import to make reusability. — Webpages will be divided into multiple components (files) and then we will be joining together in the parent component (App.jsx). — Components are reusable. Rules: 1.Component names should start with a Capital letter only. 2.Component files have to be saved with .jsx extension (recommended). Ex: App.jsx 3.We can Represent Components in 2 ways. 1. Paired tag: 2. Self—closing tag: — React components can be categorized into the following types: 1. Function—Based Components (FBC) 2. Class—Based Components (CBC) 1.Class Based Component ~ React library is mandatory to import. So import React library — Use ES6 classes - We have to use inheritance (use extends keyword) and we should have to inherit — React.Component (React is the base class where we are having a property called as Component) — Whenever we are using class based Components , render method is required , without render method your class based components will not work , your jsx will not print. This is ~ a lifecycle method. Render methods job is to call sub component and printing jsx. Whatever you write in this render method , for every update this method will rerender - Inside render method you can return JSX — Class based component is having Lifecycle methods. //! index.js or main.jsx import React from react": import ReactDOM from 'react—dom/client": import App from/App" ctDOM.createRoot (document.getElementByld("root")).render (): J! App.ja=sx import React, {Component} from "re: class App extends Component { render() { return

    Hii, I am Class Based Component

    : } export default App: ~ If you console this keyword it will point to the App. you will get state object there. which is defaultly present there in class based components . That’ s why we call them stateful components Function—Based Components: - Function—Based Components (FBC) are JavaScript functions that return JSX. elements. — They are simpler compared to class—based components and are widely used in modern React applications. — Prior to React Hooks, they were limited to stateless functionalities. ~ With the introduction of Hooks (e.g., useState, useEffect), FBCs can now manage state and lifecycle behaviors ~ Syntax: import React from "react"; const MyComponent = () => { return
    Hello, this is a functional component!
    ; as export default MyComponent; OR import React from "react"; function MyComponent() { return
    Hello, this is a functional component!
    ; } export default MyComponent; — Both arrow functions and normal functions work for functional components, but arrow functions are more commonly used in modern React. How to create components ? — At first we need a main entry point of the react js application which is index.js or main,jsx — Always one root file is required which is main js file for the react ex > index.js , main .jsx — Index.html is the main htm! file for the react . this file is not called as component , — We have to create a root component which will be rendered in this root file. Creating root component: 1. Always in sre you can create with extension as js or jsx , ex > App.js pr App.jsx first of all ,after creating root js file 2. Then Import react library only for using some functionalities like hooks and all, we don’ t need ReactDOM library because , ReactDOM is required only once to specify where we want to render our code 3. Then create a class or funi ion (as we are using functional based components nowaday's) and then return the jsx from that function 4. After that export the function 5. And then for using it , you should have to import it . and then compose 6. And then you can pass it to render method Note: App.jsx root component of the react application , but you can give any name of your choice , not only App.jsx(it should follow naming convention) Root component — We have created root component as App.jsx , now we won’ t be touching index.js, ~ We will be rendering our components in root component (App.jsx) . ~ We have to use root component to render our components , It will be working asa — wrapper for all other components JSX Expression ({}): - A JSX expression is any JavaScript code that is enclosed within curly braces {} inside your ISX elements. - You can use JSX expressions to dynamically render values, evaluate conditions, and perform calculations within your component's structure. — Example: let num1 = 20; let num2 = 10; ReactDOM.createRoot (document.getElementByld(“root") ).render (

    {num1 + num2}

    //! here"{}" is a jsx expression , because it is inside jsx
    ~ Example:2 let firstname = "Raj"; let lastname = "Patil"; let company = "TYSS"; ReactDOM.createRoot (document.getElementByld("root")).render (

    my name is {firstname}

    my last name is (lastname)

    i work at {company}

    React State: — State is plain javascript object used by react to represent an information about the component current situation. — The state is data that changes over time. — It managed in the component level. ~ State is a internal property in re will be there lly in CBC by default state object — If you want to use state in function based component . than you should use the hook called as useState() , by using useState() hook you can achieve the state object in FBC. Hooks: - Hooks are like inbuilt methods in React. — Hooks always start with a prefix word "use". - Hooks, we can use only in Function Based Components. - Whenever we want to use Hooks, ~ We have to import it from the React Library. — Import Statement is mandatory. — We have many hooks use State, useEffect, useContext, useCallback and so on. Rules for hook: 1.Always hooks should be used within a component , not outside a component 2.Hooks always starts with “use” useState(): - useState is a React Hook that allows functional components to have state. — It is used to store and update values that change over time within a component. — When a state changes, React will rerender the component by executing the function that creates the component. — Syntax: let [state, setState] =useState initial_value) ; nd in state variable initial_value will be ii, setState:It is a function to change the current value of a state. Its name can be anything. iii, useState ()- It is a Hook t falize the value. — The useState() function returns an array that contains two variables: A state (state). A function that changes the state (setState) — Always use setState() function to change the state. — Note: By convention, if a state is name, then the function that sets the state is setName. — useState can hold string , number , boolean , array , object , function. We don't have any restrictions here , we can use any data type in useState — Example: import { useState } from "react"; function Counter() { const [count, setCount] = useState (0); return (

    Count: {count}

    di — const [state, setState] = useState (initialValue) ; —“useState* takes an initial state value and returns an array with two elements: — The current state (state) — A function to update the state (setState). - 2. Updating State: — State updates trigger a re—render of the component. — You must use setState to modify the state. Props: ~ In short, we call properties as props. - Props are used to share the information between the components. — props is a way of sharing the data from one component to another component. (parent to child) as html attributes. — Props follow unidirectional flow. ic from parent component to child component. ~ By default, all the props will be stored as objects and passed to the child component. - Props are immutable, it means once the data is passed from parent component it can't be changed in child component. — You can send any type of data using props. - State is for storing data in a component level and Props is for sending Data from parent component to child component ~ Syntax: f const Parent return (
    {/* Here only for first child we are passing the props , so the props object will be there in the first child */t
    dy i export default Parent; How to consume Props in functional based components const Child = props => { console.log (props); // it will return an object containing the both the props //! {name: 'Raj', food: ‘paneer tikka’) return ( <>
    My name is {props.name} and i like to eat {props.food}
    export default Child; Passing different type of props: — For passing string data we dont need any expression we can send string normally like — Except string , if you want to pass the data then you should have to use expression Wrap the data inside an expression and then you have to send But we can consume them in the same way "Raj" salary= {20000} isAvailable= {false} isNull= {null} isUndefined= {undefined} I> Consuming data const Child = props => { let { name, salary, isAvailable, isNull, isUndefined } = props; return ( <>
    My name is {name}

    My salary is {salary}

    is Availble: {isAvailable)

    {/* here it will not print true because we know that boolean null or undefined will not be printed on the UI , boolean we can use for conditional rendering purpose */}

    { isAvailable?'yes i am available''i am not available'}

    {isNull null ? "loading" : "some content")

    {isUndefined "we got content!"}

    indefined ? "loading with undefined data" :
export default Child; Passing an object a prop: const Parent = () => { let obj = name: "shashi", salary: 10000, isAvailable: true, isNull: null, isUndefined: undefined, he return ( <> 3 he export default Parent const Child = props => { let { name, salary, isAv ble, isNull, isUndefined} = props.objectProps; let obj = new Object (isSymbol); console.log (obj); return ( <>
My name is {name}

My salary is (salary)

is Available: {isAvailable}

{""}

(isAvailable ? "yes i am available" : "i am not available")

{isNul null ? "loading" : "some content")

{isUndefined =: "we got content!"}

= undefined? "loading with undefined data":

{obj.description}

export default Child Default Props: — In React, default props allow you to specify default values for props that a component might not receive. — Generally, Props are used to share information between components and it helps to component reusability by passing different props. — What if a component was made with some prop data and that prop was not present. - So, we are able to decide what if the prop is not present. - Now the solution is passing default props. ~ If the data has not been sent then the component will consider this data. ~ The defaultProps is a react property that allows you to set default values for props objects. - Example: const Parent return (
3 as const Child2 = ({ name, company, salary }) => { return (

Name is {name}

Name is {company}

Name is {salary}

3 — So here is how we can specify default props in a component — Syntax: Ist way: Child2.defaultProps = ( name: "sachin", company: "BCCI", salary: 50000, i 2nd Way — instead of React.defaultProps you can use a simpler or operator. const Child2 = (props) => { let {name, company, salary} =props return (

Name is {name || "Shubham"}

Name is {company || "Test Yantra"}

Name is {salary || 800000}

} 3rd way — Passing default values at the time of destructuring. const Child2 = ({ name = "anurag", company = "anything", salary = 50000 }) => { return (

Name is {name}

Name is {company}

Name is (salary}

oF i Props drilling : — Props drilling is a situation in React where you pass data (props) from a parent component to a deeply nested child component through multiple intermediate components, even if they don't need the data themselves - Example: const App = 0) => { age: 30}; return ; const user = { name: "R: const Parent = ({ user }) => { return ; as const Child = ({ user }) ( return ; i const GrandChild = ({ user }) => { return

User: {user.name}

; i ~ In this case, user is passed from App ~ Parent —* Child -* GrandChild, even though Parent and Child don’ t actually use it. How to Avoid Props Drilling: 1.React Context API — Instead of passing props through multiple layers, you can store the data in a context and access it anywhere. 2.State Management Libraries (Redux, Zustand, Jotai, etc.) ~ If your app grows and needs centralized state management, using Redux or Zustand can help store and retrieve global state without drilling props. What is children Prop? The children prop in React allows components to wrap and render other components or elements. ~It is a special prop that enables componentcomposition, making React applications more flexible and reusable. Usage of children Prop: ~ It allows components to be wrapped inside other components. ~ It helps in building reusable and generic components. - It makes component composition more efficient. Context API: — This is Part of react API after 16.2 onwards. Context provides a way to pass the data through the component tree without having to pass props down manually at every level. — So that if you want to avoid props drilling. You can use context API. — Context API is the best way to avoid props drilling. ~ If it is a simple application or moderate application you can use context API . — If it is a complex application , you can go with third party libraries like mobx or redux tool. — Context API provides us to store global state. Instead of component state. You can store global state. ~ If it is a global state than easily you can access data at any level. — Simply you can consume data at whichever component you need Why do we need Context API? ~- Already we have a state, so why do we need context API? — The state belongs to the component. The state is isolated within the — component so the state is not accessible outside the component. — If you want to pass that state out of the component ,You can use props — Ex> If we have 10 components then definitely we need props drilling. You need to drill props manually at every level. So definitely this is not recommended by react. How to use Context API: — In context API we have two important things 1. Pro ler 2. Consumer — to consume the data we need provider. So in provider we need to set global state — To set the global state , react library is providing a method called as createContext method import { createContext } from "react"; Step]: create Context API ~ First, create a new context using createContext. import { createContext } from "react"; const ThemeContext = createContext (null); // returns an object with properties ad provider and consumer ~ By using createContext method you can create provider and you can consume provider Data ~ createContext will create an state and based on that state you can create provider and you can create n number of providers by using createContext method — The createContext method is coming from context API Step 2: create a Provider by using the context you created: — In provider use value prop, value is the default prop and by using value you — can set global variable in context API — Value prop is mandatory — The provider component wraps around the part of the application that needs access to the context const ThemeProvider = ({ children }) => { const [theme, setTheme] = useState ("light"); const toggleTheme = () => { setTheme ((prevTheme) => (prevTheme "light" ? "dark" : "light")); i return ( {children} vB export default ThemeProvider; useContext(): — Inreact 16.8 they introduced a hook called as useContext , this hook is the alternative for Consumer ~ This useContext is only available in functional component Step 3: Use Context in a Component — Now, access the context in a child component using useCont import { useContext } from "react"; import ThemeContext from "./ThemeContext"; const ThemeToggleButton = () => { const { theme, toggleTheme } = useContext (ThemeContext) ; return ( oF i export default ThemeToggleButton; Step 4: Wrap Application with Provider — Ensure the provider wraps the components that need access to the context. import React from "react"; import ThemeProvider from "/ThemeProvider"; import ThemeToggleButton from "./ThemeToggleButton"; const App = () => ( React Events: — Events means the interaction between a user and user interface. which is a fundamental part of developing application with complex , for ex if we click a button something will happen. - In DOM also we use Events like mouse , keyboard , screen .So this is not a new concept. ~ Here we don’ t have any big differences between DOM and React Events are the integral feature of the Web Application. ~ Events are action that happen webpage to the html elements. ~ React uses synthetic Events. Handling Events with react elements is very similar to handling events with DOM element. - There are some syntax differences. Except that we don’ t have any difference. - There are some slight differences. ~ React events are named using camelCase rather than lower case. ~ With JSX you pass a function as a event handler rather than a string. @ React events are written in camelCase syntax: @ onClick instead of onclick. @ React event handlers are written inside curly braces: @ onClic’ {shoot} instead of onclick="shoot )". @ Whenever handling events don’ t invoke Adding event handlers: — To add an event handler to a JSX element, you follow these steps: 1 First, define a function, or event handler, that will execute when an event occurs. 2.Second, pass the function as a prop of the JSX clement. const App = 0) => { return ; i export default App; — When you click the button, it does not do anything yet. To show an alert when the button is clicked, First, declare an event handler such as the handleClick function: const handleCli =O => alert (‘Clicked'); i — Second, assign the function to the onClick prop of the ; const App = () => { const handleClick = () => ( alert (‘Clicked'); as return A export default App;

You might also like