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

React Notes

1. React JS is a JavaScript library for building reusable UI components in a declarative and efficient manner. 2. It uses a virtual DOM for rendering which improves performance by only updating parts of the real DOM that actually changed. 3. Key files in a React project include node_modules, public, src, package.json and README.md. Core concepts include JSX, components, one-way data binding, and the virtual DOM.

Uploaded by

Vinita Deshpande
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

React Notes

1. React JS is a JavaScript library for building reusable UI components in a declarative and efficient manner. 2. It uses a virtual DOM for rendering which improves performance by only updating parts of the real DOM that actually changed. 3. Key files in a React project include node_modules, public, src, package.json and README.md. Core concepts include JSX, components, one-way data binding, and the virtual DOM.

Uploaded by

Vinita Deshpande
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 27

React Js Notes

 React JS is a declarative, efficient, and flexible JavaScript library for


building reusable UI components.

 Why we use ReactJS?

The main objective of ReactJS is to develop User


Interfaces (UI) that improves the speed of the apps. It uses virtual DOM
(JavaScript object), which improves the performance of the app.

 In React application, there are several files and folders in the root
directory. Some of them are as follows:

1. node_modules: It contains the React library and any other third


party libraries needed.

2. public: It holds the public assets of the application. It contains


the index.html where React will mount the application by
default on the <div id="root"></div> element.

3. src: It contains the App.css, App.js, App.test.js, index.css,


index.js, and serviceWorker.js files. Here, the App.js file always
responsible for displaying the output screen in React.

4. package-lock.json: It is generated automatically for any


operations where npm package modifies either the
node_modules tree or package.json. It cannot be published. It
will be ignored if it finds any other place rather than the top-
level package.
5. package.json: It holds various metadata required for the project.
It gives information to npm, which allows to identify the project
as well as handle the project?s dependencies.

6. README.md: It provides the documentation to read about


React topics.

 Features of react:-

7.JSX

8.Components

9.One-way Data Binding

10. Virtual DOM

A virtual DOM object is a representation of the original DOM


object. It works like a one-way data binding. Whenever
any modifications happen in the web application, the
entire UI is re-rendered in virtual DOM representation.
Then it checks the difference between the previous DOM
representation and new DOM. Once it has done, the real
DOM will update only the things that have actually
changed. This makes the application faster, and there is no
wastage of memory.

5.Simplicity

Virtual Dom:-

React creates a VIRTUAL DOM in memory.


Instead of manipulating the browser's DOM directly, React creates a virtual DOM
in memory, where it does all the necessary manipulating, before making the
changes in the browser DOM.

React only changes what needs to be changed!

React finds out what changes have been made, and changes only what needs
to be changed.

Upgrade to React 18
npm i react@latest react-dom@latest

// Before

import ReactDOM from 'react-dom';

ReactDOM.render(<App />, document.getElementById('root'));

// After

import ReactDOM from 'react-dom/client';

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

root.render(<App />);

React's goal is in many ways to render HTML in a web page.


React renders HTML to the web page by using a function
called createRoot() and its method render().

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.

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

The render() method is then called to define the React component that should
be rendered.

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 to be a <div> element and it does NOT have to have
the id='root':

React 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.

With JSX you can write expressions inside curly braces { }.


to write HTML on multiple lines, put the HTML inside parentheses:

The HTML code must be wrapped in ONE top level element.

JSX follows XML rules, and therefore HTML elements must be properly closed.

The class attribute is a much used attribute in HTML, but since JSX is rendered
as JavaScript, and the class keyword is a reserved word in JavaScript, you are
not allowed to use it in JSX.

To be able to use conditional statements in JSX, you should put


the if statements outside of the JSX, or you could use a ternary expression
instead:

React Components
Components are independent and reusable bits of code. They serve the same
purpose as JavaScript functions, but work in isolation and return HTML.

When creating a React component, the component's name MUST start with an
upper case letter.

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.

class Car extends React.Component {

render() {

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


}

Function Component

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,

Class Component:-
When creating a React component, the component's name must start with an
upper case letter.

The component has to 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.

class Car extends React.Component {

render() {

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

Component Constructor
The constructor function is where you initiate the component's properties.

In React, component properties should be kept in an object called state.

class Car extends React.Component {

constructor() {

super();

this.state = {color: "red"};

render() {

return <h2>I am a {this.state.color} Car!</h2>;

Use an attribute to pass a color to the Car component, and use it in the render()
function:

class Car extends React.Component {

render() {

return <h2>I am a {this.props.color} Car!</h2>;

}
}

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

root.render(<Car color="red"/>);

React Class Component State


React Class components have a built-in state object.

The state object is where you store property values that belongs to the
component.

When the state object changes, the component re-renders.

The state object is initialized in the constructor:

The state object can contain as many properties as you like:

Refer to the state object anywhere in the component by using


the this.state.propertyname syntax:

To change a value in the state object, use the this.setState() method.

When a value in the state object changes, the component will re-render,
meaning that the output will change according to the new value(s).

class Car extends React.Component {

constructor(props) {
super(props);

this.state = {

brand: "Ford",

model: "Mustang",

color: "red",

year: 1964

};

changeColor = () => {

this.setState({color: "blue"});

render() {

return (

<div>

<h1>My {this.state.brand}</h1>

<p>

It is a {this.state.color}
{this.state.model}

from {this.state.year}.

</p>

<button

type="button"

onClick={this.changeColor}

>Change color</button>

</div>

);

Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate
during its three main phases.

The three phases are: Mounting, Updating, and Unmounting.

Mounting
Mounting means putting elements into the DOM.
1. constructor:-

The constructor() method is called before anything else, when the


component is initiated, and it is the natural place to set up the
initial state and other initial values.

The constructor() method is called with the props, as arguments, and


you should always start by calling the super(props) before anything else,
this will initiate the parent's constructor method and allows the
component to inherit methods from its parent (React.Component).

2.getDerivedStateFromProps

The getDerivedStateFromProps() method is called right before rendering the


element(s) in the DOM.

This is the natural place to set the state object based on the initial props.

It takes state as an argument, and returns an object with changes to


the state.

3.render

The render() method is required, and is the method that actually outputs the
HTML to the DOM.

4.componentDidMount

The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already
placed in the DOM.
Updating:-
The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the


component's state or props.

React has five built-in methods that gets called, in this order, when a
component is updated:

1.getDerivedStateFromProps

Also at updates the getDerivedStateFromProps method is called. This is the first


method that is called when a component gets updated.

This is still the natural place to set the state object based on the initial prop

2.shouldComponentUpdate

In the shouldComponentUpdate() method you can return a Boolean value that


specifies whether React should continue with the rendering or not.

The default value is true.

3.render

The render() method is of course called when a component gets updated, it has
to re-render the HTML to the DOM, with the new changes.
4.getSnapshotBeforeUpdate

In the getSnapshotBeforeUpdate() method you have access to


the props and state before the update, meaning that even after the update, you
can check what the values were before the update.

f the getSnapshotBeforeUpdate() method is present, you should also include


the componentDidUpdate() method, otherwise you will get an error.

5.componentDidUpdate

The componentDidUpdate method is called after the component is updated in the


DOM.

Unmounting
The next phase in the lifecycle is when a component is removed from the DOM,
or unmounting as React likes to call it.

React has only one built-in method that gets called when a component is
unmounted:

The componentWillUnmount method is called when the component is about to be


removed from the DOM.

React Props
Props are arguments passed into React components.

Props are passed to components via HTML attributes.

props stands for properties.


The component receives the argument as a props object:

Props are also how you pass data from one component to another, as
parameters.

If you have a variable to send, and not a string as in the example above, you
just put the variable name inside curly brackets:

Note: React Props are read-only! You will get an error if you try to change their
value.

React Events
ust like HTML DOM events, React can perform actions based on user events.

React has the same events as HTML: click, change, mouseover etc.

Adding Events
React events are written in camelCase syntax:

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot} instead of onClick="shoot()".

unction Football() {
const shoot = () => {

alert("Great Shot!");

return (

<button onClick={shoot}>Take the shot!</button>

);

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

root.render(<Football />);

Passing Arguments
To pass an argument to an event handler, use an arrow function.

function Football() {

const shoot = (a) => {

alert(a);

}
return (

<button onClick={() => shoot("Goal!")}>Take the shot!</button>

);

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

root.render(<Football />);

React Conditional Rendering


In React, you can conditionally render components.

There are several ways to do this.

if Statement
We can use the if JavaScript operator to decide which component to render.

unction Goal(props) {

const isGoal = props.isGoal;

if (isGoal) {
return <MadeGoal/>;

return <MissedGoal/>;

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

root.render(<Goal isGoal={false} />);

Logical && Operator


Another way to conditionally render a React component is by using
the && operator.

We can embed JavaScript expressions in JSX by using curly braces:

function Garage(props) {

const cars = props.cars;

return (

<>

<h1>Garage</h1>

{cars.length > 0 &&


<h2>

You have {cars.length} cars in your garage.

</h2>

</>

);

const cars = ['Ford', 'BMW', 'Audi'];

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

root.render(<Garage cars={cars} />);

Ternary Operator
Another way to conditionally render elements is by using a ternary operator.

function Goal(props) {

const isGoal = props.isGoal;

return (

<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }

</>

);

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

root.render(<Goal isGoal={false} />);

React Lists
In React, you will render lists with some type of loop.

The JavaScript map() array method is generally the preferred method.

Keys
Keys allow React to keep track of elements. This way, if an item is updated or
removed, only that item will be re-rendered instead of the entire list.

function Car(props) {

return <li>I am a { props.brand }</li>;

}
function Garage() {

const cars = [

{id: 1, brand: 'Ford'},

{id: 2, brand: 'BMW'},

{id: 3, brand: 'Audi'}

];

return (

<>

<h1>Who lives in my garage?</h1>

<ul>

{cars.map((car) => <Car key={car.id} brand={car.brand}


/>)}

</ul>

</>

);

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

root.render(<Garage />);

React Forms
Handling forms is about how you handle the data when it changes value or gets
submitted.

In HTML, form data is usually handled by the DOM.

In React, form data is usually handled by the components.

When the data is handled by the components, all the data is stored in the
component state.

You can control changes by adding event handlers in the onChange attribute.

We can use the useState Hook to keep track of each inputs value and provide a
"single source of truth" for the entire application.

You can control the submit action by adding an event handler in


the onSubmit attribute for the <form>:

You can control the values of more than one input field by adding
a name attribute to each element.

To access the fields in the event handler use


the event.target.name and event.target.value syntax.

import { useState } from 'react';


import ReactDOM from 'react-dom/client';

function MyForm() {

const [inputs, setInputs] = useState({});

const handleChange = (event) => {

const name = event.target.name;

const value = event.target.value;

setInputs(values => ({...values, [name]: value}))

const handleSubmit = (event) => {

event.preventDefault();

alert(inputs);

return (
<form onSubmit={handleSubmit}>

<label>Enter your name:

<input

type="text"

name="username"

value={inputs.username || ""}

onChange={handleChange}

/>

</label>

<label>Enter your age:

<input

type="number"

name="age"

value={inputs.age || ""}

onChange={handleChange}

/>

</label>
<input type="submit" />

</form>

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

root.render(<MyForm />);

In React the value of a textarea is placed in a value attribute. We'll use


the useState Hook to manage the value of the textarea:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [textarea, setTextarea] = useState(

"The content of a textarea goes in the value attribute"

);
const handleChange = (event) => {

setTextarea(event.target.value)

return (

<form>

<textarea value={textarea} onChange={handleChange} />

</form>

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

root.render(<MyForm />);

In React, the selected value is defined with a value attribute on the select tag:

function MyForm() {

const [myCar, setMyCar] = useState("Volvo");


const handleChange = (event) => {

setMyCar(event.target.value)

return (

<form>

<select value={myCar} onChange={handleChange}>

<option value="Ford">Ford</option>

<option value="Volvo">Volvo</option>

<option value="Fiat">Fiat</option>

</select>

</form>

You might also like