Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

React Js

Introduction of react.
React is a JavaScript library for building user interfaces. It was voted the most loved in the
“Frameworks, Libraries, and Other Technologies” category of Stack Overflow’s 2017 Developer
Survey.

React is a JavaScript library and React applications built on it run in the browser, NOT on the server.
Applications of this kind only communicate with the server, when necessary, which makes them
amazingly fast compared to traditional websites that force the user to wait for the server to re-
render entire pages and send them to the browser.

React is used for building user interfaces - what the user sees on their screen and interacts with to
use your web app. This interface is split up into components, instead of having one huge page you
break it up into smaller pieces known as components. In more general terms, this approach is
called Modularity.

⦁ It is declarative: React uses a declarative paradigm that makes it easier to reason about your
application.

⦁ It is efficient: React computes the minimal set of changes necessary to keep your DOM up-to-
date.

⦁ And it is flexible: React works with the libraries and frameworks that you already know.

Features of ReactJs
JSX: JSX is an extension to java script. Though it is not mandatory to use JSX in react, it is one of
the good features and easy to use.

Components: Components are like pure java script functions that help make the code easy by
splitting the logic into reusable independent code. We can use components as functions and
components as classes. Components also have a state, props which makes life easy. Inside a class,
the state of each of the props is maintained.

Virtual DOM: React creates a virtual DOM, i.e., in-memory data -structure cache. Only the final
changes of DOM have later updated in the browsers DOM.

JavaScript Expressions: JS expressions can be used in the .jsx files using curly brackets, for
example {}.

Advantages of ReactJs
⦁ ReactJS uses virtual DOM that makes use of in-memory data-structure cache, and only the
final changes are updated in browsers DOM. This makes the app faster.

⦁ You can create components of your choice by using the react component feature. The
components can be reused and helpful in code maintenance.

⦁ ReactJs is an open-source java script library, so it is easy to start with.

⦁ ReactJS has become extremely popular in a short span and maintained by Facebook and
Instagram. It is used by many famous companies like Apple, Netflix, etc.
⦁ Facebook maintains ReactJS, the library, so it is well maintained and kept updated.

⦁ ReactJS can be used to develop rich UI for both desktop and mobile apps.

⦁ Easy to debug and test as most of the coding is done in JavaScript rather than on HTML.

Disadvantages of ReactJs
⦁ Most of the code is written in JSX, i.e., HTML and CSS are part of java script, it can be
quite confusing as most other frameworks prefer keeping HTML separate from the java script
code.

⦁ The file size of ReactJS is large.

Virtual DOM
React JS Virtual DOM is an in-memory representation of the DOM. DOM refers to the Document
Object Model that represents the content of XML or HTML documents as a tree structure so that
the programs can be read, accessed, and changed in the document structure, style, and content.

Rules for React


1. Component First Letter will be Capital

2. Components contain own Template and Logic

3. Template is the HTML to be return

4. Logic is the JavaScript Statements

5. App (root component) is the main component of React and its render in root Element of the
index.html by index.js file.

6. App components contain a function which return something which look like an HTML
Template.

7. This is not an HTML. This is what we called JSX.

8. With JSX, we can easily create these components.

9. Babel convert JSX to HTML file and render into the HTML Dom.

10. This conversion is all done in Background

11. For Example. In JSX instead class attribute we use class Name which is having Camel case and
when this executed its converted into class as HTML attributes.

12. In version 17, we do not need to import react. (Check your React Version)

13. You can pass the dynamic values to React Components.

14. But you cannot pass object to the component Directly.

15. For Objects you can use states.

16. Install Simple React VS Code Extension

17. Install React Dev tools Chrome Extension for Testing/Debugging React App

Create React App and folder structure.


There are many ways to create react app.

Prerequisites
1. Install Node.js and NPM

2. Install Visual Studio Code

Create React app


We will use create-React-app NPX tool to create a simple React app.

Open Node.js command prompt.

Navigate to the respective folder, where you want to create React app.

Type the command given below in a console to install create-React-app using NPX tool.

Navigate to the myBlog folder.

Type the command code. in a console to open the app in Visual Studio code.

React app will have the folder structure given below.

Type the command given below in a console to launch React app in the Browser.

NPM start.

NPM install

NPM run dev

Create by vite
NPM create vite@latest.

Cd “project Name”

NPM install

NPM run dev

React JSX
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. But
instead of using regular JavaScript, react code should be written in something called JSX.

Let us see a sample JSX code:

Example: -

const element = <h1>This is sample JSX</h1>;

JSX (JavaScript Extension), is a React extension which allows writing JavaScript code that looks like
HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that
HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e.,
transpiler like babel) to transform HTML-like syntax into standard JavaScript objects that a
JavaScript engine will parse.
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file
where you write JavaScript code, then preprocessor will transform these expressions into actual
JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.

Why JSX?
⦁ It is faster than normal JavaScript as it performs optimizations while translating to regular
JavaScript.

⦁ It makes it easier for us to create templates.

⦁ Instead of separating the markup and logic in separated files, react uses components for
this purpose. We will learn about components in detail in further articles.

Using JavaScript expressions in JSX


In React we are allowed to use normal JavaScript expressions with JSX. To embed any JavaScript
expression in a piece of code written in JSX we will have to wrap that expression in curly braces {}.

Consider the below program, written in the app.js file:

const name = "Learner";

function App () {

return (

<div className="App">

<h1>Hello {name}, Welcome to firstReactApp.</h1>

</div>

);

export default App;

Output: Hello Listener, welcome to firstReactApp.

Wrapping elements or Children in JSX


Consider a situation where you want to render multiple tags at a time. To do this we need to wrap
all this tag under a parent tag and then render this parent element to the HTML. All the sub-tags
are called child tags or children of this parent element.

JSX Styling
React always recommends using inline styles. To set inline styles, you need to use camelCase
syntax. React automatically allows appending px after the number value on specific elements. The
following example shows how to use styling in the element.

Example
import React from "react";

const cssStyle = {

fontSize: "24px",

color: "white",

backgroundColor: "black",

padding: "10px",

width: "500px",

textAlign: "center",

borderRadius: "10px",

};

function App () {

return (

<div className="App">

<h2 style={cssStyle}> FirstReactApp -Lets Code Together</h2>

</div>

);

export default App;

JSX Comments
JSX allows us to use comments that begin with /* and ends with */ and wrapping them in curly
braces {} just like in the case of JSX expressions. Below example shows how to use comments in JSX.

Example

import React from "react";

function App () {

return (

<div className="App">

<h1>Hello from Beta-Labs</h1>

{/* This is a comment in JSX */}

</div>

);

export default App;


React Components
Components are the building blocks of any React app and a typical React app will have many of
these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e.,
properties(props) and returns a React element that describes how a section of the UI (User
Interface) should appear.

Every React component have their own structure, methods as well as APIs. They can be reusable as
per your need. For better understanding, consider the entire UI as a tree. Here, the root is the starting
component, and each of the other pieces becomes branches, which are further divided into sub-
branches.

In ReactJS, we have two types of components. They are

1. Functional Components
2. Class Components

Function Component
A function component is the simplest form of a React component. It is a simple function with a
simple syntax.

EXAMPLE:

MyComponent1.js

import React from "react";

function MyComponent1(props) {

return <h1>This is Function Component </h1>;

}
export default MyComponent1;

We have created a function called MyComponent1 that returned h1 tag as shown above. The name
of the function acts as an element, as shown below:

The Component MyComponent1 is used as an Html tag, i.e., < MyComponent1 /> and same is
exported using export.

Let us now use this component in index.js file as shown below:

app.js

import MyComponent1 from ". /MyComponent1";

function App () {

return (

<div className="App">

<MyComponent1 />

</div>

);

export default App;

Class Component
Class components are more complex than functional components. It requires you to extend from
React. Component and create a render function which returns a React element. Here is a ReactJS
example that uses a class as a component.

MyComponent2.js

import React from "react";

class MyComponent2 extends React.Component {

render () {

return <h1>This is Class Component </h1>;

export default MyComponent2;

The Component MyComponent2 is used as an Html tag, i.e., < MyComponent2 /> and same is
exported using export. We can use MyComponent2 component in App.js file as follows:

App.js

import MyComponent1 from ". /MyComponent1";


import MyComponent2 from ". /MyComponent2";
function App () {
return (
<div className="App">
<MyComponent1 />
<MyComponent2 />
</div>
);
}
export default App;

The Component MyComponent2 is used as an Html tag i.e., < MyComponent2 />

React Fragment
We know that we make use of the render method inside a component whenever we want to
render something to the screen. We may render a single element or multiple elements, though
rendering multiple elements will require a ‘div’ tag around the content as the render method will
only render a single root node inside it at a time.

Example: Create a React app and edit the App.js file from the src folder as:

import React from "react";


function App () {
return (
// Extraneous div element
<div>
<h1>Importance of React Fragment</h1>
<p>
Fragments let you group a list of children without adding extra
nodes to the DOM.
</p>
</div>
);
}
export default App

As we saw in the above code when we are trying to render more than one root element, we must
put the entire content inside the ‘div’ tag which is not loved by many developers. So, in React 16.2
version, Fragments were introduced, and we use them instead of the extraneous ‘div’ tag.

Shorthand Fragment: The output of the first code and the code above is the same but the main
reason for using is that it is a tiny bit faster when compared to the one with the ‘div’ tag inside it, as
we didn’t create any DOM node. Also, it takes less memory. Another shorthand also exists for the
above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’.

Note: The shorthand syntax does not accept key attributes in that case you have to use the
<React.Fragments> tag.

Syntax:
<>
<h2>Child-1</h2>
<p> Child-2</p>
</>;

React Props
Props are an optional input, and can be used to send data to the component. Props are a way of
making components easily and dynamically customizable. It’s important to note that props are read-
only and that a component must never modify the props passed to it. This also makes them come in
handy when you want to display fixed values.

Now that you know about props, make use of them in the components that we have just created
with a custom name appended to it.

Make changes to the code between the script tags in your App.js document to make it look like this:

import MyComponent1 from "./MyComponent1";


import MyComponent2 from "./MyComponent2";

function App () {
return (
<div className="App">
<MyComponent1 name="Beta-Labs" />
<MyComponent2 name="Beta-Labs" />
</div>
);
}
export default App;
Using Props with Function Components

1. An argument (props) is passed to the functional component. Recall that since a single argument
is being passed to function. Passing this argument lets the component know to expect some data to
be passed to it.
2. Within MyComponent1.jsx, the name you want rendered to the screen is passed in by specifying
{props.propValue} within the component’s tag.
3. In the h3 tag, {} are used to print the name that is added to the props object when it’s passed in
via the component’s tag. Notice that the name attribute is accessed using the dot syntax.

There is no limit to how many props can be supplied to a component. Now Make changes to the code
of MyComponent1.jsx to pass props to the class component:

Using Props with Class Components


Adding props to class components is a similar process to the one used in the functional component
above. There are three notable changes:
1. Props is not passed as an argument to the class
2. The name attribute is accessed using this.props.name instead of props.name
3. To pass props to the class component, we just define the normal constructor function (which
receives a props object) and call the super method to honour the inheritance of the component.
React State

Props are pieces of data passed into a child component from the parent while state is data
controlled within a component

What is State?

The state is an updatable structure that is used to contain data or information about the component.
The state in a component can change over time. The change in state over time can happen as a
response to user action or system event. A component with the state is known as stateful
components. It is the heart of the react component which determines the behavior of the component
and how it will render. They are also responsible for making a component dynamic and interactive.

Here is an example showing how to use state:

import React, { Component } from "react";


class Test extends React.Component {
constructor() {
super();
this.state = {
id: 1,
name: "Pankaj",
};
}
render() {
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.name}</p>
</div>
);
}
}
export default Test;

Update a component’s state


State should not be modified directly, but it can be modified with a special method called setState( ).

this.state.id = "2021"; // wrong


this.setState({ // correct
id: "2021"

});

What happens when state changes?

A change in the state happens based on user-input, triggering an event, and so on. Also, react
components (with state) are rendered based on the data in the state. State holds the initial
information. So, when state changes, React gets informed and immediately re-renders the DOM –
not the whole DOM, but only the component with the updated state. This is one of the reasons
why React is fast.

And how does React get notified? You guessed it: with setState( ). The setState( ) method triggers
the re-rendering process for the updated parts. React gets informed, knows which part(s) to change,
and does it quickly without re-rendering the whole DOM.

• In summary, there are 2 important points we need to pay attention to when using state:

3. State shouldn’t be modified directly – the setState( ) should be used


4. State affects the performance of your app, and therefore it shouldn’t be used unnecessarily

Important: Can I use state in every component?

Another important question you might ask about state is where exactly we can use it. In the early
days, state could only be used in class components, not in functional components.

That is why functional components were also known as stateless components. However, after the
introduction of React Hooks, state can now be used both in class and functional components.

If your project is not using React Hooks, then you can only use state in class components.

Differences between props and state

Finally, let’s recap and see the main differences between props and state:

• Components receive data from outside with props, whereas they can create and manage their own
data with state
• Props are used to pass data, whereas state is for managing data
• State data can be modified by its own component, but is private (cannot be accessed from outside)
• Props can only be passed from parent component to child (unidirectional flow)
• Modifying state should happen with the setState () method
• Data from props is read-only and cannot be modified by a component that is receiving it from
outside.

React Components Lifecycle

We have learned so far that the React web applications are actually a collection of independent
components that run according to the interactions made with them. Each component in React has a
life cycle that you can monitor and change during its three main phases. There are three phases:
Mounting, Updating, and Unmounting. You can use life-cycle methods to run a part of code at
particular times in the process or application. You can refer to the below diagram to get a visual idea
of the life-cycle methods and their interactions in each phase.

Mounting

Mounting is the phase when the component is mounted on the DOM and then rendered on the
webpage. We call these methods in the following order when an element is being created and
inserted into the DOM:

• componentWillMount()
• render ()
• componentDidMount()

componentWillMount(): This function is called right before we mount the component on the DOM.
So, after this method executes, the component gets mounted on the DOM. It executes this method
before the first render of the React application. So, all the tasks that have to be done before the
component mounts are defined in this method.

render (): This function mounts the component on the browser.

componentDidMount(): We invoke this function right after the component is mounted on the DOM
i.e., this function gets called once after the render () function is executed for the first time. Generally,
in React applications, we do the API calls within this method.

Updating

We call the methods in this phase whenever State or Props in a component get updated. This allows
the React application to “react” to user inputs, such as clicks and pressing keys on the keyboard, and
ultimately create a responsive web user interface. These methods are called in the following order
to carry on the update of the component:

• componentWillReceiveProps()
• setState()
• shouldComponentUpdate()
• componentWillUpdate()
• render ()
• componentDidUpdate()

componentWillRecieveProps(): We call This function before a component gets its props reassigned.

setState(): This function can be called explicitly at any moment. This function is used to update the
state of a component.

shouldComponentUpdate(): This function is called before rendering a component and tells React
whether it should update the component on receiving new props or state. It takes the new Props and
new State as the arguments and returns whether or not to re-render the component by returning
either True or False.

componentWillUpdate(): This function is called once before the render () function is executed after
the update of State or Props.

render (): The component gets rendered when this function is called.

componentDidUpdate(): This function is called once after the render () function is executed after the
update of State or Props.

Unmounting
This is the last phase of the life cycle of the component where the component is unmounted from
the DOM. This phase has only one method:
componentWillUnmount(): This function is called once before we remove the component from the
page, and this marks the end of the life cycle.

Now that we are familiar with all the life-cycle methods of React components, let us now look at an
example to see how each function is implemented in the application code:

DisplayCycle.js
import React from "react";
import DisplayChild from ". /DisplayChild";
class DisplayCycle extends React.Component {
constructor(props) {
super(props);
this.state = {name: "Pankaj"};
console.log("Constructor");
}
componentWillMount() {
console.log ("componentWillMount Parent");
}
componentDidMount() {
console.log ("componentDidMount Parent");
}
shouldComponentUpdate() {
console.log ("shouldComponentUpdate parent");
return true;
}
componentWillUpdate() {
console.log("componentWillUpdate() called");
}

componentDidUpdate() {
console.log("componentDidUpdate() called");
}
componentWillUnmount() {
console.log("componentWillUnmount() called");
}
switchState = () => {
this.setState({name: "pankaj Kapoor"});
};
render () {
console.log ("render Parent");
return (
<div>
<input type="text" value={this.state.name} />
<DisplayChild firstname={this.state.name} />
<button onClick={this.switchState}>Click Me</button>
</div>
);
}
}
export default DisplayCycle;

React Hooks
Earlier on in React, components were either class components or functional components. Functional
components were Javascript functions that accepted props (data) to display and returned JSX.

Class components typically required more code but could store state variables and could use lifecycle
methods. This made class components the go-to option for making API calls, processing user input, etc.
Functional components became useful helpers for class components.

With the release of React 16.8 in 2019, React Hooks have finally become available to use in our production
applications. This allows React developers to make functional components stateful. Instead of using a
class component to hold stateful logic, we can use functional components.

React Hooks are not available in class-based components — but instead they allow you to use React
without JavaScript classes. If you prefer to use functions instead of classes (which is recommended in
JavaScript) you can simply start using Hooks without worrying about migrating your whole apps to classes.

Hooks enable you to use “class-features” In React by providing a set of built-in functions such as:

• The useState() hook for using states from function components,


• The useEffect() hook for performing side effects from function components (It's equivalent to
life-cycle methods like componentDidMount, componentDidUpdate, and
componentWillUnmount in React classes).

Hook State
let’s set up a component with state, the hooks way.

import React from "react";


const HookDemo = () => {
return (
<div>
<h2>React Hooks</h2>
</div>
);
};
export default App;

And now, let’s use a React hook. We’ll add in some state to the component. To do so, we’ll import the
useState hook from React at the top of the App.js file:

import React, { useState } from 'react';

Then we’ll apply the useState hook at the top of the App component function, to set up state
functionality for the stuRoll:
const HookDemo = () => {
const [stuRoll, setStuRoll] = useState();

There are three aspects to the useState hook:

1. The argument to useState is its initial value. Therefore, with useState(), we are setting the initial
value of stuRoll to a blank value.

2. The useState method destructures your state object into an array of two values. The first one is
the current value of the variable that is being tracked in the component state. Therefore, in const
[stuRoll, setStuRoll] = useState(), stuRoll represents that current value. It becomes a constant that
can be used in the component code.

3. The second value returned from the useState function is a function itself. This function updates
the paired state variable. So setStuRoll updates the stuRoll value.

Within the App component, let’s create a helper method, called updateData. With this method, the
input element will set the stuRoll in the hook state. How?
This helper will call the new setStuRoll function and update the student Rollno.
const ReactDemo = () => {
const [stuRoll, setStuRoll] = useState(0);

const updateData = () => {

setStuRoll(10);

console.log ("Updated RollNo", stuRoll);


};

return (
<div>
<h2>Hooks | Function Component Based</h2>
<h3>RollNo: {stuRoll}</h3>
<button onClick={updateData}>Update</button>
</div>
);
};
export default ReactDemo;
Comparison to traditional class Component state
Let’s compare the App component function above with the more traditional class component state
approach:
import React, {Component} from "react";
class StateDemo extends React.Component {
constructor () {
super ();
this.state = {
stuRoll: 0,
};
}
updateData = () => {
this.setState({ stuRoll: 10});
};
render () {
return (
<div>
<h2>State | Class Component Based </h2>
<h3>RollNo: {this.state.stuRoll}</h3>
<button onClick={this.updateData}>Update</button>
</div>
);
}
}
export default StateDemo;

Take note of the differences between this function version and the class version. It’s already much more
compact and easier to understand than the class version, yet they both do exactly the same thing. Let’s
go over the differences:

• The entire class constructor has been replaced by the useState Hook, which only consists of a
single line.
• Because the useState Hook outputs local variables, you no longer need to use this keyword to
reference your function or state variables. Honestly, this is a major pain for most JavaScript
developers, as it’s not always clear when you should use this.
• The JSX code is now cleaner as you can reference local state values without using this.state.

Hook with Multiple states


import React, { useState, useEffect } from "react";
const ReactDemo = () => {
const [stuRoll, setStuRoll] = useState(0);
const [stuName, setStuName] = useState("---");
// Update the data of the component
const updateData = () => {
setStuRoll(10);
setStuName("Pankaj");
};
return (
<div>
<h2>Hooks with Multiple States</h2>
<h3>RollNo: {stuRoll}</h3>
<h3>Name: {stuName}</h3>
<button onClick={updateData}>Update</button>
</div>
);
};
export default ReactDemo;
The Rules of Hooks

5. Hooks can only be called at the Top Level; it can't be called inside the loops or condition or nested
functions.
6. Hooks can only be called in the React Function or Custom Hooks, never use hooks in the regular
javascript function.

Hooks Effect
The Hooks Effect enables us to conduct collateral effects within the components function. The Hooks
Effect will not use the lifecycle methods of the components, and these methods exist in the class
components. Hooks Effect is similar to componentDidUpdate(), componentDidMount() lifecycle
methods.

import React, { useState, useEffect } from "react";


const ReactDemo = () => {
const [stuRoll, setStuRoll] = useState(0);
const [stuName, setStuName] = useState("---");
// Similar to componentDidMount() and componentDidUpdate
useEffect(() => {
console.log ("Hooks Effects called ");
});
// Update the data of the component
const updateData = () => {
setStuRoll(10);
setStuName("Pankaj");
};
return (
<div>
<h2>Hooks with UseEffect</h2>
<h3>RollNo: {stuRoll}</h3>
<h3>Name: {stuName}</h3>
<button onClick={updateData}>Update</button>
</div>
);
};
export default ReactDemo;

In the above code, we invoke “useEffect” to inform the React to execute the “effect” method after
reddening the modifications in the DOM. As we declare the effects in a component, the effects can use
the state and props. React implements the effects after each render. Effects may also define how to do
“clean up”.
Side effects contain usual properties that every web application have to conduct, like:
· DOM Updation
· Consuming and Retrieving data from an API Server.
· Establishing Subscription

Side Effects
we categorize side effects into two types:
Effects with Cleanup: After updating the DOM, we have to clean up some effects. For example, when we
need to establish a subscription for any explicit data source, it is essential to clean up the memory to
ensure that there is no memory leak.
Effects without Cleanup: We use Effects without Cleanup in effect that does not obstruct the browser in
screen updation. Examples of Effects that do not need cleanup are Network requests, Manual DOM
mutations, etc.

React Events
In web development, events represent actions that happen in the web browser. By responding to events
with event handlers, you can create dynamic JavaScript applications that respond to any user action,
including clicking with a mouse, scrolling along a webpage, touching a touch screen, and more.

In React apps, you can use event handlers to update state data, trigger prop changes, or prevent default
browser actions. React has its own event handling system which is very similar to handling events on DOM
elements. The react event handling system is known as Synthetic Events. SyntheticEvent closely emulates
the standard browser event but provides more consistent behavior for different web browsers.

Handling events with react have some syntactic differences from handling events on DOM. These are:

7. React events are named as camelCase instead of lowercase.


8. With JSX, a function is passed as the event handler instead of a string. For example:

Event declaration in plain HTML:


<button onclick="showMessage()">
Hello JavaTpoint
</button>

Event declaration in React:


<button onClick={showMessage}>
Hello JavaTpoint
</button>

3. In react, we cannot return false to prevent the default behavior. We must call preventDefault event
explicitly to prevent the default behavior. For example:

In plain HTML, to prevent the default link behavior of opening a new page, we can write:

<a href="#" onclick="console.log ('You had clicked a Link.'); return false">


Click_Me
</a>

In React, we can write it as:

function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log ('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}

In the above example, e is a Synthetic Event which defines according to the W3C spec.

Now let us see how to use Event in React.

onClick Event handler in React


The React onClick event handler enables you to call a function and trigger an action when a user clicks an
element, such as a button, in your app.

To listen to events in React, add the onClick attribute, which is the event handler, to the target element.
This specifies the function to be executed when that element is clicked.

import React, {Component} from "react";


class ShowAlert extends Component {
showAlert() {
alert ("I'm an alert");
}
render () {
return <button onClick={this.showAlert}>show alert</button>;
}
}
export default ShowAlert;
Handling events in class components
In JavaScript, class methods are not bound by default. Therefore, it’s necessary to bind functions to the
class instance.

Binding in the render () method: One way to resolve the problem of binding is to call bind in a render
function. This is done by binding it in the render () function. This method requires calling. bind(this) in the
render () function.

<button onClick={this.showAlert.bind(this)}>show alert</button>

Binding in the constructor () method: If binding in the render doesn’t work for you, you can bind in the
constructor. See an example below:

class ShowAlert extends Component {

constructor(props) {
super(props);

this.showAlert = this.showAlert.bind(this);

The first this.showAlert refers to the showAlert method. Since this is done in the constructor, this refers
to the ShowAlert class component.

The second this.showAlert is also referring to the same showAlert() method, but we are now calling. bind
() on it.

The final this is the context we are passing to. bind (), and it refers to the ShowAlert class component.

It’s also important to note that if showAlert isn’t bound to the class instance, it won’t be able to access
this.setState because this will be undefined. This is another important reason to bind event handling
functions.

Binding in the arrow function: You can handle events in class components by binding them with the fat
arrow function. ES7 class properties enable bindings at the method definition, as shown in the example
below. By definition, an arrow function expression has a shorter syntax than a function expression and
does not have its own this, arguments, super, or new.target.

showAlert= () => {
alert ("I'm an alert");
}

onChange Event handler in React


In the below example, we have used only one component and adding an onChange event. This event will
trigger the changeText function, which returns the company name.

import React, {Component} from "react";


class DemoOnChange extends React.Component {
constructor(props) {
super(props);
this.state = {
tutorialName: "",
};
}
changeText(event) {
this.setState({
tutorialName: event.target.value,
});
}
render () {
return (
<div>
<h2>onChange Event Example</h2>
<label htmlFor="name">Enter Tutorial name: </label>
<input
type="text"
id="companyName"
onChange={this.changeText.bind(this)}
/>
<h4>You entered: {this.state.tutorialName}</h4>
</div>
);
}
}
export default DemoOnChange;
onSubmit Event handler in React

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

Example

import React, {Component} from "react";

class MyForm extends React.Component {

constructor(props) {

super(props);

this.state = {username: ""};

mySubmitHandler = (event) => {

event.preventDefault();

alert ("You are submitting " + this.state.username);

};

myChangeHandler = (event) => {

this.setState({username: event.target.value });

};

render () {

return (

<form onSubmit={this.mySubmitHandler}>

<h2>onSubmit Event Example</h2>

<p>Enter your name, and submit:</p>


<h1>{this.state.username}</h1>

<input type="text" onChange={this.myChangeHandler} />

<input type="submit" />

</form>

);

export default MyForm;

Note that we use event.preventDefault() to prevent the form from actually being submitted. Displaying
List in React

Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying
menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating
lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to
do this in detail further in this article.

Using JSX we can show lists using JavaScript's built-in Array.map() method. The. map () method is often
used to take one piece of data and convert it to another. In our scenarios, we are taking data and
converting it to a piece of our view.

A Simple Example
Let's say we have a list of arrays that we want to show in a list:

import React from "react";

export default function ArrayMap() {

const arr = [10, 20, 30, 40, 50];

const newArr = arr.map(function (num) {

console.log ("Num", num);

return <li> {num * 2} </li>;

});

console.log ("Old Array", arr);

console.log ("New Array", newArr);

return <ul>{newArr}</ul>;
}

This component uses Array’s built-in map function to create a new array newArr that has the same
number of elements, and where each element is the result of calling the function, you provide. The {}
brackets are used to render the array of elements.

import React from "react";

export default function ArrayMap() {

const arr = [10, 20, 30, 40, 50];

return (

<ul>
{
arr.map((num) => {

return <li>{num}</li>;
})}

</ul>

);
}

The above is the shorthand code for write the map function. Since we are not doing anything in the
function's block body, we can also refactor it to a concise body and omit the return statement and the
curly braces for the function body:

return (
<ul>

{arr.map(num =><li>{num}</li>)}

</ul>
);

Rendering lists inside Components

So, from the component’s point of view, we have to pass a list to a component using props and then use
this component to render the list to the DOM. We can update the above code in which we have directly
rendered the list to now a component that will accept an array as props and returns an unordered list.

const mylist = [10, 20, 30, 40, 50];


const App = () => <ListComponent list={mylist} />;

const ListComponent = ({list}) => (

<ul>

{list.map((item) => (

<li>{item}</li>

))}

</ul>
);
export default App;

You can see in the above output that the unordered list is successfully rendered to the browser, but a
warning message is logged to the console.

Warning: Each child in an array or iterator

should have a unique "key" prop

The above warning message says that each of the list items in our unordered list should have a unique
key. A “key” is a special string attribute you need to include when creating lists of elements in React. We
will discuss about keys in detail in further articles. For now, let’s just assign a key to each of our list items
in the above code.

Below is the example where we display the list of Objects with keys.

Display Object List in React


Displaying items from a list of objects in React is very simple. We can iterate over a list of objects using
the. map () method in React JSX. Here is the example in which we mapped a list of objects and displayed
them in the React app.

import React, { useState } from "react";

import "../node_modules/bootstrap/dist/css/bootstrap.css";

export default function DemoMap() {

const [user, addUser] = useState([


{
id: 1,
username: "pankkap",
password: "pankaj123",
},
{
id: 2,
username: "manishkumar",
password: "manish456",
},
{
id: 3,
username: "sachinyadav",
password: "sachin789",
},
]);

const renderUser = (user, index) => {


return (

<tr key={index}>

<td>{user.id} </td>

<td>{user.username}</td>

<td>{user.password}</td>

</tr>
);
};
return (

<div className="container mt-3">

<table class="table">

<thead class="thead-light">

<tr>

<th>#</th>

<th>Username</th>

<th>Password</th>

</tr>

</thead>

<tbody>{user.map(renderUser)} </tbody>
</table>

</div>
);
}

The key attribute is necessary for React to identify which items have changed, are added, or are removed.
Keys should be given to the elements inside the array to give the elements a stable identity. Since React
uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we
provided a unique id to every list item.

React Router

As opposed to traditional multi-page applications, SPAs only maintain one HTML file, commonly
index.html. Instead of serving a different HTML file for each path, SPAs depend on client-side routing.
React Router is a popular client-side routing library.

Routing is a process in which a user is directed to different pages based on their action or request. ReactJS
Router is mainly used for developing Single Page Web Applications (SPA). React Router is used to define
multiple routes in the application. When a user types a specific URL into the browser, and if this URL path
matches any 'route' inside the router file, the user will be redirected to that particular route.

Why use React router?


React Router plays an important role to display multiple views in a single page application. Without React
Router, it is not possible to display multiple views in React applications. Most of the social media websites
like Facebook, Instagram uses React Router for rendering multiple views.

React Router uses component structure to call components, which display the appropriate information.
React router also allows the user to utilize browser functionality like the back button, and the refresh
page, all while maintaining the correct view of the application.

React Router Installation


React contains three different packages for routing. These are:

1. react-router: It provides the core routing components and functions for the React Router
applications.

2. react-router-dom: It is used for web applications design.

3. react-router-native: It is used for mobile applications.


Step 1: Install React Router

It is not possible to install react-router directly in your application. To use react routing, first, you need to
install react-router-dom modules in your application. The below command is used to install react router
dom.

npm install react-router-dom


Step 2: Make Four components.

In our project, we will create four more components in the directory called Pages along with App.js, which
is already present.

Pages/Home.js

import React from "react";


export default function Home () {
return (
<div>
<h1>Home Page</h1>
</div>
);
}

Pages/About.js

import React from "react";

export default function About () {


return (
<div>
<h1>About Page</h1>
</div>
);

Pages/Contact.js

import React from "react";

export default function Contact () {


return (
<div>
<h1>Contact Page</h1>
</div>
);
}

Pages/Navbar.js

import React from "react";


export default function Navbar () {
return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid">
<ul className="nav navbar-nav">
<li className="nav-item">
<a href="/" className="nav-link" exact>
Home
</a>
</li>
<li className="nav-item">
<a href="/about" className="nav-link" exact>
About
</a>
</li>
<li className="nav-item">
<a href="/contact" className="nav-link" exact>
Contact
</a>
</li>
</ul>
</div>
</nav>
);
}

Step 3: Setup App.js for Routing

App.js

import React from 'react';


import Navbar from ". /Pages/Navbar";
import Home from ". /Pages/Home";
import About from ". /Pages/About";
import Contact from ". /Pages/Contact";
function App () {
return (
<div className="App">
<Navbar />
<Home />
<About />
<Contact />
</div>
);
}

export default App;


For Routing, open the app.js file and import all the four component files in it. Here, you need to import
line:

import { BrowserRouter as Router, Swtich, Route} from "react-router-dom";

which helps us to implement the Routing. Now, our app.js file looks like below.

BrowserRouter as Router
First, you'll need to set up your app to work with React Router. Everything that gets rendered will need
to go inside the <BrowserRouter> element, but we just rename BrowserRouter as Router only to reduce
the long name of the BrowserRouter. so, wrap your App in those first. It's the component that does all
the logic of displaying various components that you provide it with.

import React from "react";


import { BrowserRouter as Router, Swtich, Route} from "react-router-dom";

import Navbar from ". /Pages/Navbar";


import Home from ". /Pages/Home";
import About from ". /Pages/About";
import Contact from ". /Pages/Contact";
function App () {
return (
<Router>
<div className="App">
<Navbar />
<Home />
<About />
<Contact />
</div>
</Router>
);
}
export default App;

Switch
Next, in your App component, add the Switch element (open and closing tags). These ensure that only
one component is rendered at a time. It checks each route for a match sequentially and stops once the
first match is found.

function App () {
return (
<Router>
<div className="App">
<Navbar />
<switch>
<Home />
<About />
<Contact />
</switch>
</div>
</Router>
);
}

You notice that we put <Navbar /> component outside the switch, because we want that navbar will be
visible on each component that render.

Route

It's now time to add your <Route> tags. These are the links between the components and should be
placed inside the <Switch> tags.

To tell the <Route> tags which component to load, simply add a path attribute and the name of the
component you want to load with component attribute. The <Route> will return null in case the specified
URL doesn’t match the defined path.

function App () {
return (
<Router>
<div className="App">
<Navbar />
<switch>
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/contact" exact component={Contact} />
</switch>
</div>
</Router>
);
}

When the route matches /, the application shows the Dashboard component. When the route is changed
by clicking the “About” link to /about, the Dashboard component is removed and the About component
is inserted in the DOM.

Notice the exact attribute. Without this, path="/" would also match /about, since / is contained in the
route. However, we want ‘/’ to match only our render function, hence using ‘exact’ explicitly achieves
this.
Step 4: Adding Navigation Link
Link

Sometimes, we want to need multiple links on a single page. When we click on any of that particular Link,
it should load that page which is associated with that path without reloading the web page. To do this,
we need to import <Link> component in the Navbar.js file. The Link component is used to trigger new
routes. You import it from react-router-dom, and you can add the Link components to point at different
routes, with the to attribute. It is the equivalent of anchor tags: <a> </a>.

So now we should update Navbar.js for providing Navigation link in react application by replacing <a> tag
to <Link> Tag and 'href' to 'to' attribute.

Pages/Navbar.js
import React from "react";
import {Link} from "react-router-dom";

export default function Navbar () {


return (
<nav className="navbar navbar-expand-lg navbar-dark bg-dark">
<div className="container-fluid">
<Ul class Name="nav navbar-nav">
<li class Name="nav-item">
<Link to="/" class Name="nav-link" exact>
Home
</Link>
</li>
<li class Name="nav-item">
<Link to="/about" class Name="nav-link" exact>
About
</Link>
</li>
<li class Name="nav-item">
<Link to="/contact" class Name="nav-link" exact>
Contact
</Link>
</li>
</Ul>
</div>
</nav>
);
}

404 Page Not Found


A common use case for when you’re building a web app is to have a “catch all” route that will be rendered
if none of your other routes match. A common example of this would be a 404 page.
To create a client side "404 not found" fallback all you need to do is make use of a <Route /> component
with a non-greedy matching path. Create you're Not Found component, i.e. the page which will display
404 error message:

Pages/NotFound.js
import React from "react";

export default function Not Found () {


return (
<div>
<h3>404 page not found</h3>
<p>We are sorry but the page you are looking for does not exist. </p>
</div>
);

Let's add <Not Found /> component to routes configuration, using * as a value of the path parameter to
get a non-greedy matching.

It is important to remember that the 404 route needs to be declared in the very bottom of your route's
configuration, so the <Route /> is only mounted if any of the routes' path declared above are not
matched:

App.js

import Not Found from ". /Pages/Not Found";

function App () {
return (
<Router>
<div class Name="App">
<Navbar />
<switch>

{/* Other Page Routes */}

<Route component= {Not Found} />


</switch>
</div>
</Router>
);
}
export default App;
React Project Link for reference: - https://github.com/bansalkrishna438/React1234

Using PixiJs in React


• React 17 and 18 support
• PixiJS v6 and v7 support
• react-spring compatible animated components
1. Create a new React project with Vite:
# for typescript use "--template react-ts"
npx create-vite@latest --template react my-app
cd my-app
npm install
2. Install Pixi-React dependencies:
npm install pixi.js @pixi/react
3. Replace App.jsx with the following:
import './App.css';
import { useMemo } from 'react';
import { BlurFilter, TextStyle } from 'pixi.js';
import { Stage, Container, Sprite, Text } from '@pixi/react';
export const App = () => {
const blurFilter = useMemo(() => new BlurFilter(2), []);
const bunnyUrl = 'https://pixijs.io/pixi-react/img/bunny.png';
return (
<Stage x={800} y={600} options={{ background: 0x1099bb }}>
<Sprite image={bunnyUrl} x={300} y={150} />
<Sprite image={bunnyUrl} x={500} y={150} />
<Sprite image={bunnyUrl} x={400} y={200} />
<Container x={200} y={200}>
<Text
text="Hello World"
anchor={0.5}
x={220}
y={150}
filters={[blurFilter]}
style={
new TextStyle({
align: 'center',
fill: '0xffffff',
fontSize: 50,
letterSpacing: 20,
dropShadow: true,
dropShadowColor: '#E72264',
dropShadowDistance: 6,
})
}
/>
</Container>
</Stage>
);
};
4. Run the app:
npm run dev

You might also like