React JS Update V2
React JS Update V2
Features of ReactJS
JSX : JSX is an extension to javascript. 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 javascript 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 has 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 also helpful in code
maintenance.
Reactjs is an open-source javascript library, so it is easy to start with.
ReactJS has become very 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
Here, are cons/ drawbacks of using ReactJS:
Most of the code is written in JSX, i.e., Html and css are part of javascript,
it can be quite confusing as most other frameworks prefer keeping Html
separate from the javascript code.
The file size of ReactJS is large.
Fast - Feel quick and responsive through the Apps made in React can
handle complex updates.
Modular - Allow you to write many smaller, reusable files instead of
writing large, dense files of code. The modularity of React is an attractive
solution for JavaScript's visibility issues.
Scalable - React performs best in the case of large programs that display
a lot of data changes.
Flexible - React approaches differently by breaking them into
components while building user interfaces. This is incredibly important in
large applications.
Popular - ReactJS gives better performance than other JavaScript
languages due to t’s implementation of a virtual DOM.
Easy to learn - Since it requires minimal understanding of HTML and
JavaScript, the learning curve is low.
Server-side rendering and SEO friendly - ReactJS websites are famous
for their server-side rendering feature. It makes apps faster and much
better for search engine ranking in comparison to products with client-
side rendering. React even produces more opportunities for website SEO
and can occupy higher positions on the search result’s page.
Reusable UI components - React improves development and debugging
processes.
Community - The number of tools and extensions available for ReactJS
developers is tremendous. Along with impressive out-of-box
functionalities, more opportunities emerge once you discover how giant
the React galaxy is. React has a vibrant community and is supported by
Facebook. Hence, it’s a reliable tool for website development.
Create your First React Application
Prerequisite
Open Command Prompt, check the node and npm version
node –-version
npm –-version
Open New Terminal inside the Visual Studio code and type the following
command to create your first React project.
File Structure
node_modules: This folder contains all the dependencies and sub-
dependencies of packages used by the current React app.
public: This folder contains static assets of the web application. index.html
provides the entry point for the web app.
src: This folder contains JavaScript that will be processed by webpack. It's the
place where all your React-related source code lives. You'll work primarily in this
folder to develop your app.
.gitignore: A text file that tells the source control tool git which files or folders
to ignore in a project.
package.json: Primarily used to store the metadata associated with the project
as well as to store the list of dependency packages.
package-lock.json: According to the npm Docs, package-lock.json is
automatically generated for any operations where npm modifies either the
node_modules tree or package.json. It describes the exact tree that was
generated—subsequent installs can generate identical trees regardless of
intermediate dependency updates.
README.md: This file contains the basic information to get started with Create
React App.
In the terminal redirect to the directory where the first react app is created
You can start the development web server by executing the following command
in the terminal:
In the browser you will see the output as shown below,
It leads to warning.
Practice 2_2 (my-second-react-app)
Output:
React State
React components has a built-in state object.
The state object is where you store property values that belong to the
component.
When the state object changes, the component re-renders.
State of a React component is an object that contains information.
State object stores values of the properties related to component.
Hence whenever there is change in the properties related to component, the
value associated with the state object changes and the component will be
re-rendered.
State can be used only in class components (later we will look into class and
functional components in detail with example) and state is generally
updated by event handlers.
ReactJS Props:
Props in ReactJS are used to send data to components.
Props are immutable, its values cannot be modified by a component that is
receiving it from outside.
Props are used either in state or functional components.
Props are used to pass data between parent and child components.
State Example 1
import React, { Component } from 'react'
export default class App extends Component {
constructor(){
super()
this.state={city:"Salem", pincode: 636005}
}
render() {
return (
<div>
<h1>Main Component</h1>
<h2>My City is {this.state.city}</h2>
<h2>Pincode {this.state.pincode}</h2>
</div>
)
}
}
State Example 2
import React, { Component } from 'react'
Example 6
import React, { Component } from 'react'
class MyComponent extends React.Component {
render() {
return (
// Accessing the prop 'name' passed to this component
<h1>Hello, {this.props.name}!</h1>
);
}
}
export default class App extends Component {
constructor(props) {
super(props);
// Initialize state to manage the prop value
this.state = {
name: 'John'
};
}
Class (index.js)
class Demo{
methodone(){
var a = 5;
var b = 10;
var c = a+b;
document.getElementById("root").innerHTML = c;
}
}
var myDemo = new Demo();
myDemo.methodone();
or
var a = function(){
var a = 5;
var b = 10;
var c = a+b;
document.getElementById("root").innerHTML = c;
}
a();
or
var a = () =>{
var a = 5;
var b = 10;
var c = a+b;
document.getElementById("root").innerHTML = c;
}
a();
or
var a = (x) =>{
var a = 5;
var b = 10;
var c = a+b+x;
document.getElementById("root").innerHTML = c;
}
a(20);
Use of let
var n = (x) =>{
var a = 5;
if (a===5){
let a = 10;
document.getElementById("root").innerHTML = a;
}
}
n(20);
The above program outputs 10 because a was local to the functions (let)
var n = (x) =>{
var a = 5;
if (a===5){
let a = 10;
}
document.getElementById("root").innerHTML = a;
}
n(20);
The above program outputs 5 because a was global to the functions (var)
React JSX
JSX – Javascript XML
Use to write HTML in React
Use to write HTML elements in JS and place them in the DOM without any
createElement()
Example (with createElement) – index.js
const myele = React.createElement("h1",{},"Hello World");
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);
You can see the output in the browser as Hello World
Example (without createElement) – index.js (Use of JSX)
const myele = <h1>Hello World!!!</h1>;
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);
You can see the output in the browser as Hello World!!!
Example – add CSS and HTML together using JSX – index.js
var myStyle = {
color: "red",
textAlign: "center"
}
const myele = <div style={myStyle}>
<h1>Welocome</h1>
<h2>React Project</h2>
<p>R u there?</p>
</div>
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);
Output
In the above example, we can also add expression within the HTML tags as shown
below
Example – add external CSS and HTML together using JSX – index.js
import './index.css';
const myele = <div>
<h1 className='header'>Welocome {5+10}</h1>
<h2>React Project</h2>
<p>R u there?</p>
</div>
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(myele);
index.css
.header{
color:blueviolet;
text-align: center;
}
Output
React Components
function Header(){
return <div>
<h1>Sona College of Technology</h1>
<h2>logo</h2>
</div>
}
function Sidebar(){
return <h1>Sidebar</h1>
}
function Navbar(){
return <h1>Navbar</h1>
}
function MyWebsite(){
return <div>
<Header/>
<Sidebar/>
<Navbar/>
</div>
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyWebsite/>);
Pre-requisites:
App.js
In real life, you will have to create much more complicated layouts, and using the
above method for creating components will no longer be feasible.
The following example creates another component that will demonstrate how
cumbersome it can get to create complicated components with multiple children.
App.css
div.container {
margin: 6rem auto;
width: fit-content;
font-size: 3rem;
text-align: center;
}
h2 {
margin: 1rem;
font-family: "Bebas Neue";
}
p {
margin: 1rem;
font-family: "Asap Condensed";
font-weight: 400;
}
App.js
import React from 'react'
import './App.css'
function Country(props) {
return React.createElement(
'div', {
className: "container"
}, React.createElement(
'h2', {
className: "country-name"
}, `Country Name: ${props.name}`),
React.createElement('p', {
className: "capital"
}, `Capital: ${props.capital}`),
React.createElement('p', {
className: "population"
}, `Population: ${props.population}`));
}
const App = () => {
return (
<Country name= 'United States' capital= 'Washington, D.C.' population
='332 million'/>
)
}
export default App
Composing Component
return (
<Button onClick={onClick}>
<img src="/logos/logo.svg" alt='logo'/>
Click me!
</Button>
);
}
export default App
But we're not limited to the children prop. We can create more specific props that
can accept components as well:
import React from 'react'
const Button = ({ onClick, icon, children }) => (
<button onClick={onClick}>{icon}{children}</button>
);
const App = () => {
const onClick = () => alert('Hey ���');
return (
<Button onClick={onClick}>
<img src="/logos/logo.svg" alt='logo'/>
Click me!
</Button>
);
}
export default App
And that is the essence of component composition: a simple yet incredibly
powerful pattern that makes React components highly reusable.
When working on React projects, you'll continuously find yourself refactoring
components to be more generic through component composition so that you can
use them in multiple places.
import React from 'react'
const WelcomePage = ({ userName }) => {
return (
<>
<WelcomeMessage userName={userName} />
{/** Some other welcome page code */}
</>
);
}
const WelcomeMessage = ({ userName }) => {
return (
<h1>Hey, {userName}!</h1>
);
}
const App = () => {
const userName = 'Joe';
return (
<WelcomePage userName={userName} />
);
}
export default App
Here's a visualization of how the components are structured:
Our app, after removing one layer with component composition. We don't need to
pass down userName twice anymore—we just pass it to WelcomeMessage right
away.
Now, I don't say that either of these examples is bad code and that prop drilling
should be avoided at all costs.
However, it's a useful pattern to be aware of if prop-drilling becomes an issue.
body {
font-family: Sans-serif;
height: 300vh;
}
.progress {
top: 10px;
left: 10px;
position: fixed;
background-color: white;
padding: 5px;
border-radius: 5px;
}
.content {
margin-top: 70px;
}
This code will cause a lot of re-renders, and we can assume that the blog post
content contains a lot more components—so re-renders will be expensive.
If we move the logic to a separate component and use component composition to
glue them together, the number of re-renders goes from 61 (on my computer) to 1 for the
content section of the Post component.
All I did was moving the state updates to PostLayout and rendering the post
content as a prop.
App.js