Unit2 ReactJS
Unit2 ReactJS
Unit2 ReactJS
ReactJs follows the Model View Controller (MVC) architecture, and the view layer is
accountable for handling mobile and web apps.
React is famous for building single-page applications and mobile apps.
ReactJS History
Jordan Walke created React, who worked as a software engineer in Facebook has first released an
early React prototype called "FaxJS.”
In 2011, React was first deployed on Facebook's News Feed, and later in 2012 on Instagram.
ReactJS Features
JSX is a preferable choice for many web developers. It isn't necessary to use JSX in React
development, but there is a massive difference between writing react.js documents in JSX and
JavaScript. JSX is a syntax extension to JavaScript. By using that, we can write HTML structures in
the same file that contains JavaScript code.
React.js is designed so that it will only support data that is flowing downstream, in one direction. If
the data has to flow in another direction, you will need additional features.
React contains a set of immutable values passed to the component renderer as properties in HTML
tags. The components cannot modify any properties directly but support a call back function to do
modifications.
3. Virtual Document Object Model (VDOM)
React contains a lightweight representation of real DOM in the memory called Virtual DOM.
Manipulating real DOM is much slower compared to VDOM as nothing gets drawn on the screen.
When any object’s state changes, VDOM modifies only that object in real DOM instead of updating
whole objects.
That makes things move fast, particularly compared with other front-end technologies that have to
update each object even if only a single object changes in the web application.
4. Extensions
React supports various extensions for application architecture. It supports server-side rendering, Flux,
and Redux extensively in web app development. React Native is a popular framework developed
from React for creating cross-compatible mobile apps.
5. Debugging
Testing React apps is easy due to large community support. Even Facebook provides a small browser
extension that makes React debugging easier and faster.
Step 2: Once it is done change your directory to the newly created application using the following
command
cd foldername
Step 3: Now inside App.js and write down the following code as shown below:
import React from 'react';
import './App.css';
function App() {
return (
<h1> Hello World! </h1>
);
}
.gitignore
This file is used by source control tool to identify which files and folders should be included or
ignored during code commit
package.json
This file contains dependencies and scripts required for the project.
Src folder
Index.js
index.js is the file that will be called once we will run the project.
App.js
App.js is a component that will get loaded under index.js file. If we do any change in app.js file
HTML component and save it it will reflect in localhost://3000
React Component
A Component is considered as the core building blocks of a React application. It makes the task of
building UIs much easier. Each component exists in the same space, but they work independently
from one another and merge all in a parent component, which will be the final UI of your application.
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.
JSX
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the
same file where you write JavaScript code, and then pre-processor will transform these expressions
into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and
children.
<div>Hello React app</div>
Corresponding Output
It is faster than regular JavaScript because it performs optimization while translating the code to
JavaScript.
Instead of separating technologies by putting markup and logic in separate files, React uses
components that contain both. We will learn components in a further section.
JSX Attributes
JSX use attributes with the HTML elements same as regular HTML. JSX uses camel case naming
convention for attributes rather than standard naming convention of HTML such as a class in HTML
becomes className in JSX because the class is the reserved keyword in JavaScript. We can also use
our own custom attributes in JSX. For custom attributes, we need to use data- prefix. In the below
example, we have used a custom attribute data-demo Attribute as an attribute for the <p> tag.
2. As Expressions: We can specify the values of attributes as expressions using curly braces {}:
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.
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.
NOTE: JSX cannot allow to use if-else statements. Instead of it, you can use conditional (ternary)
expressions.
1. import React, { Component } from 'react';
2. class App extends Component{
3. render(){
4. var i = 5;
5. return (
6. <div>
7. <h1>{i == 1 ? 'True!' : 'False!'}</h1>
8. </div>
9. );
10. }
11. }
12. export default App;
Now we want to replace python with java script. For that, we need to create a new array.
Instead of this, we can just traverse to languages[2] and update only the element. Instead of redoing
the whole thing, we just changed the element which we needed to update. The same thing is done by
Virtual DOM. Instead of updating all the node elements, it just updates the changed elements.
Virtual DOM does the same thing. Instead of updating all the node elements, it just updates the
changed elements. Virtual DOM does the same thing. Virtual DOM does the same thing. Instead of
updating all the node elements, it just updates the changed elements.
ReactDOM.render() will create a Virtual and real DOM tree of the first load. When events like click,
keypress, or API response occur, Virtual DOM tree elements are notified for state or prop change; if
that state or props are updated, then the node elements are updated. When changes are done in UI, the
changes are also done in Virtual DOM. Instead of updating all the nodes, Virtual DOM updates only
those components in which changes are made .
Once Virtual DOM contains all the updated changes, it is then compared with the Real DOM and the
difference is calculated between them.
Once Virtual DOM contains all the updated changes it is then compared with the Real DOM and the
difference is calculated between them.
Once the difference is calculated the real DOM will update only the new components that have
actually changed. This is called Reconciliation. Virtual DOM is faster and more effective than
Real DOM as it just focuses on the updated components instead of updating the entire DOM.
React Components
Earlier, the developers write more than thousands of lines of code for developing a single page
application. These applications follow the traditional DOM structure, and making changes in them
was a very challenging task. If any mistake found, it manually searches the entire application and
update accordingly. The component-based approach was introduced to overcome an issue. In this
approach, the entire application is divided into a small logical group of code, which is known as
components.
A Component is considered as the core building blocks of a React application. It makes the task of
building UIs much easier. Each component exists in the same space, but they work independently
from one another and merge all in a parent component, which will be the final UI of your application.
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.
Functional Components
Class Components
Class Components
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. You can pass data
from one class to other class components. You can create a class by defining a class that extends
Component and has a render function. Valid class component is shown in the below example.
When creating a React component, the component’s name MUST start with an upper-case letter.
Class Component
To define a React component class, your class needs to extend with React.Component.
The render() method must be defined in the class component. Other React.Component methods are
optional like constructor() componentDidMount(), etc.
class Hello extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
2. Handling Props
3. Handling States
4. Lifecycle Methods
6. Higher-Order Components
7. Error Boundaries
1. Components Rendering
In the class component, the render() method is used for rendering the JSX by
extending React.Component
The functional component is just a plain JavaScript function that returns JSX.
The first two programs are a perfect example of component rendering.
// Class component
class Hello extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
//Function component
function Hello() {
return <h1>Hello World!</h1>;
}
2. Handling Props
The props stands for properties and is passed into the React component. It’s also used for passing
data from one component to another.
Class component with Props
this.props used to access our name props.
class Hello extends React.Component {
render() {
return <h1>Hello {this.props.name}!</h1>;
}
}
render() {
return(
<div>
<h1>Hello {this.props.name}!</h1>
<h2>Time Now {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
Functional Component with Lifecycle Hook Methods
We converted above the clock class component into a functional component using
the useEffect hook.
The useEffect return method is used to clean up.
function Clock(props) {
const [date, setDate] = React.useState(new Date());
React.useEffect(() => {
var timerID = setInterval(() => tick(), 1000);
function tick() {
setDate(new Date());
}
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {date.toLocaleTimeString()}.</h2>
</div>
);
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
Winner: Class Component
The functional component useEffect is confusing due to using the same hook for all the lifecycle
methods. In the class component, we can directly use the
methods componentDidMount, componentWillUnmount, etc.
5. Accessing Components Children
The special children prop is used to access the component inside content or component like
<Layout>inside content</Layout>.
Class Component
this.props.children is used for class components.
class Layout extends React.Component {
render() {
return(
<div>
<h1>Hello {this.props.name}!</h1>
<div>{this.props.children}</div>
</div>
);
}
}
Props
In ReactJS, the data can be passed from one component to another component using these props,
similar to how the arguments are passed in a function. Inside the component, we can add the attributes
called props; however, we cannot change or modify props inside the component as they are
immutable.
Using the “this.props”, we can make the props available inside the components. Then, the dynamic
data can be rendered through the render method. We need to add the props to the reactDOM.render()
in the Main.js file of our ReactJS project of ReactJS if we need immutable data in the component.
Then we can use it in the component where we want to use those dynamic data.We pass the dynamic
data for name attribute within the App component through the render method called reactDOM.render.
The below code is for App.js. Here, we are using the dynamic data for the name attribute which the
Main.js file has passed as props, and making the props available within this App component using
“this.props”.
import React, { Component } from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1> Welcome to the { this.props.name} </h1>
<p> <h4> Here you will get to know so many things and your knowledge will be enhanced .
</h4> </p>
</div>
);
}
}
App.defaultProps = {
We can create, handle, or manage our data within the component using the state object. Data can be
passed by the props but the data cannot be passed by state itself. Using the state, the data is managed
internally within the component.
We can combine both the state and props within our application in ReactJS. The steps for this
combination process of the states and props within our ReactJS are as follows: First, the state needs to
be set within our parent component. Then, the state can be passed as the props within the child
component.
The code given below is for the App.js file. This code shows how we can set the state in our parent
component and then pass it within the child component as the props and use it.
Example:
We pass the dynamic data for name attribute within the App component through the render method
called reactDOM.render.
The below code is for App.js. Here, we are using the dynamic data for the name attribute which the
Main.js file has passed as props, and making the props available within this App component using
“this.props”.
SN Props State
3. Props allow you to pass data from one State holds information about the
component to other components as an components.
argument.
4. Props can be accessed by the child component. State cannot be accessed by child
components.
5. Props are used to communicate between States can be used for rendering
components. dynamic changes with the component.
8. Props are external and controlled by whatever The State is internal and controlled by
renders the component. the React Component itself.
Destructuring
The destructuring is an ES6 feature that makes it possible to unpack values from arrays or properties
from objects into distinct variables. In React, destructuring props and states improve code readability.
Destructuring was introduced in ES6. It’s a JavaScript feature that allows us to extract multiple
pieces of data from an array or object and assign them to their own variables. Consider we have an
employee object with the following properties:
const employee = {
firstName: "Ramesh",
lastName: "Fadatare",
emailId: ramesh@gmail.com
App component
We are passing employee firstName, lastName and email to Employee component using props:
function App() {
return (
<div className="App">
<Employee firstName = "Ramesh" lastName = "Fadatare" emailId = "ramesh@gmail.com" />
</div>
);
}
Destructuring state
Class Component(Stateful)
constructor(){
super();
this.state={
render(){
return (
<div>
<p>{this.state.first_name}</p>
<p>{this.state.last_name}</p>
</div>
}
export default StateExample;
Functional Component(Stateless)
function Example(props) {
return(
<div>
<p>{props.first_name}</p>
<p>{props.last_name}</p>
</div>
Stateful Components
Stateful components are those components which have a state. The state gets initialized in the
constructor. It stores information about the component’s state change in memory. It may get changed
depending upon the action of the component or child components.
Stateless Components
Stateless components are those components which don’t have any state at all, which means you can’t
use this.setState inside these components. It is like a normal function with no render method. It has
no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other
hooks. When react renders our stateless component, all that it needs to do is just call the stateless
component and pass down the props.
A stateless component renders output which depends upon props value, but a stateful component
render depends upon the value of the state. A functional component is always a stateless component,
but the class component can be stateless or stateful.
Having a parent component pass data down to its children also assures that if there is any debugging
needed regarding state management, we can go to the parent component to see what’s up, instead of
checking state in each child component. All the children components have to worry about is
receiving the information as props properly (no pun intended).
So presentational components can vary depending on what information it receives. The difference is
that a stateful component keeps track of the information itself, instead of just taking it via props and
outputting it.
If information is completely static and you know it will never change, we have a very ‘presentational’
component indeed.
<div>
<ol>
</ol>
</div>
Parent-child communication
Following are the steps to pass data from child component to parent component:
In the parent component, create a callback function. This callback function will retrieve the data from
the child component.
Pass the callback function to the child as a props from the parent component.
The child component calls the parent callback function using props and passes the data to the parent
component.
Filepath- src/App.js
state = {
name: "",
this.setState({name: childData})
render(){
Filepath- src/component/Child.js
this.props.parentCallback(event.target.myname.value);
event.preventDefault();
render(){
return(
<div>
<br></br><br></br>
<br></br><br></br>
</form>
</div>