Unit-2 Fundamentals of React - Js
Unit-2 Fundamentals of React - Js
js
Overview of React.Js
React is an open source, JavaScript library for developing user interface (UI) in web application. React
is developed and released by Facebook. Facebook is continuously working on the React library and
enhancing it by fixing bugs and introducing new features.
ReactJS is a simple, feature rich, component based JavaScript UI library. It can be used to develop
small applications as well as big, complex applications. ReactJS provides minimal and solid feature set
to kick-start a web application. React community compliments React library by providing large set of
ready-made components to develop web application in a record time. React community also provides
advanced concept like state management, routing, etc., on top of the React library.
React versions
The initial version, 0.3.0 of React is released on May, 2013 and the latest version, 17.0.1 is released on
October, 2020. The major version introduces breaking changes and the minor version introduces new
feature without breaking the existing functionality. Bug fixes are released as and when necessary.
React follows the Sematic Versioning (semver) principle.
Features
The salient features of React library are as follows −
Extensible architecture
Component based library
JSX based design architecture
Declarative UI library
Benefits
Few benefits of using React library are as follows −
Easy to learn
Easy to adept in modern as well as legacy application
Faster way to code a functionality
Availability of large number of ready-made component
Large and active community
Applications
Few popular websites powered by React library are listed below −
Therefore, a new technology ReactJS framework invented which remove this drawback. ReactJS
allows you to divide your entire application into various components. ReactJS still used the
same traditional data flow, but it is not directly operating on the browser's Document Object
Model (DOM) immediately; instead, it operates on a virtual DOM. It means rather than
manipulating the document in a browser after changes to our data, it resolves changes on a
DOM built and run entirely in memory. After the virtual DOM has been updated, React
determines what changes made to the actual browser's DOM. The React Virtual DOM exists
entirely in memory and is a representation of the web browser's DOM. Due to this, when we
write a React component, we did not write directly to the DOM; instead, we are writing virtual
components that react will turn into the DOM.
React create-react-app
Starting a new React project is very complicated, with so many build tools. It uses many
dependencies, configuration files, and other requirements such as Babel, Webpack, ESLint before
writing a single line of React code. Create React App CLI tool removes all that complexities and makes
React app simple. For this, you need to install the package using NPM, and then run a few simple
commands to get a new React project.
The create-react-app is an excellent tool for beginners, which allows you to create and run React
project very quickly. It does not take any configuration manually. This tool is wrapping all of the
required dependencies like Webpack, Babel for React project itself and then you need to focus on
writing React code only. This tool sets up the development environment, provides an excellent
developer experience, and optimizes the app for production.
Requirements
The Create React App is maintained by Facebook and can works on any platform, for example,
macOS, Windows, Linux, etc. To create a React Project using create-react-app, you need to have
installed the following things in your system.
Let us check the current version of Node and NPM in the system.
$ node -v
Run the following command to check the NPM version in the command prompt.
$ npm -v
Installation
Here, we are going to learn how we can install React using CRA tool. For this, we need to follow the
steps as given below.
Install React
We can install React using npm package manager by using the following command. There is no need
to worry about the complexity of React installation. The create-react-app npm package manager will
manage everything, which needed for React project.
NOTE: We can combine the above two steps in a single command using npx. The npx
is a package runner tool which comes with npm 5.2 and above version.
C:\Users\javatpoint> npx create-react-app reactproject
The above command will take some time to install the React and create a new project with the name
"reactproject." Now, we can see the terminal as like below.
The above screen tells that the React project is created successfully on our system. Now, we need to
start the server so that we can access the application on the browser. Type the following command in
the terminal window.
$ cd my-app
$ npm start
NPM is a package manager which starts the server and access the application at default
server http://localhost:3000. Now, we will get the following screen.
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.
Next, if we want to make the project for the production mode, type the following command. This
command will generate the production build, which is best optimized.
$ npm build
React renders HTML to the web page by using a function called ReactDOM.render().
The purpose of the function is to display the specified HTML code inside the specified HTML element.
There is another folder in the root directory of your React project, named "public". In this folder, there
is an index.html file.
You'll notice a single <div> in the body of this file. This is where our React application will be
rendered.
Example:
Display a paragraph inside an element with the id of "root":
Const root=ReactDOM.createRoot(document.getElementById(‘root’));
Root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Create a variable that contains HTML code and display it in the "root" node:
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>John </td>
</tr>
<tr>
<td>Elsa </td>
</tr>
</tbody>
</table>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Output:
It does NOT have to be a <div> element and it does NOT have to have the id='root':
Example:
The root node can be called whatever you like:
<body>
<header id=”root”></header>
</body>
Const root=ReactDOM.createRoot(document.getElementById(‘root’));
Root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
MS. ESHA PATEL Page 11
Unit-2: Fundamentals of React.js
React Components
Components are like functions that return HTML elements.
Components are independent and reusable bits of code. They serve the same purpose as JavaScript
functions, but work in isolation and return HTML.
Components come in two types, Class components and Function components, in this tutorial we will
concentrate on Function components.
In older React code bases, you may find Class components primarily used. It is now suggested to use
Function components along with Hooks, which were added in React 16.8. There is an optional section
on Class components for your reference.
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.
Example:
Index.html :
<!DOCTYPE html>
<html lang="en">
<head>
render() {
return (
<div>
<h1>React Class Component</h1>
</div>
)
}
}
Output :
Function Component
Here is the same example as above, but created using a Function component instead.
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.
Example:
Index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-react-app"/>
MS. ESHA PATEL Page 14
Unit-2: Fundamentals of React.js
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Index.js :
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
)
}
Output :
Rendering a Component
Now your React application has a component called Car, which returns an <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Example:
Display the Car component in the "root" element:
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Components in Components
We can refer to components inside other components:
Example:
Use the Car component inside the Garage component:
function Car() {
return (
<div>
<h2>I am a Car!</h2>
</div>
);
return (
<div>
<Car />
</div>
);
import './index.css';
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Output:
Components in Files
React is all about re-using code, and it is recommended to split your components into separate files.
To do that, create a new file with a .js file extension and put the code inside it:
Example:
This is the new file, we named it "App.js":
function App() {
return (
<div>
<h2>I am a Car!</h2>
</div>
);
To be able to use the Car component, you have to import the file in your application.
Example:
Now we import the "App.js" file in the application, and we can use the App component as if it was
created here.
import './index.css';
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
React Props
props stands for properties.
React Props are like function arguments in JavaScript and attributes in HTML.
React Props
React Props are like function arguments in JavaScript and attributes in HTML.
To send props into a component, use the same syntax as HTML attributes:
Example:
Add a "brand" attribute to the Car element:
import './index.css';
root.render(
<React.StrictMode>
<App brand="Ford"/>
</React.StrictMode>
);
return (
<div>
</div>
Output:
Pass Data
Props are also how you pass data from one component to another, as parameters.
Example:
Send the "brand" property from the Garage component to the Car component:
function Car(props) {
return (
<div>
<Car brand="Ford"/>
</div>
);
Output:
Note: React Props are read-only! You will get an error if you
try to change their value.
With the addition of Hooks, Function components are now almost equivalent to Class components.
The differences are so minor that you will probably never need to use a Class component in React.
Even though Function components are preferred, there are no current plans on removing Class
components from React.
This section will give you an overview of how to use Class components in React.
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 via a render() function.
Components come in two types, Class components and Function components, in this chapter you will
learn about Class components.
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.
Example:
Now your React application has a component called App, which returns a <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Example:
Display the App component in the "root" element:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
if Statement
We can use the if JavaScript operator to decide which component to render.
Example:
We'll use these two components:
function MissedGoal() {
return <h1>MISSED!</h1>;
}
function MadeGoal() {
return <h1>Goal!</h1>;
}
Example:
Now, we'll create another component that chooses which component to render based on a condition:
)
}
function MadeGoal() {
return (
<div>
<h1>Goal!</h1>
<MissedGoal />
</div>
)
}
export default function abc() {
const isGoal =false;
if (isGoal) {
return <MissedGoal />;
}
return <MadeGoal />;
}
Output:
function MissedGoal() {
return (
<div>
<h1>MISSED!</h1>
</div>
)
}
function MadeGoal() {
return (
<div>
<h1>Goal!</h1>
<MissedGoal />
</div>
)
}
export default function abc() {
const isGoal =true;
if (isGoal) {
return <MissedGoal />;
}
return <MadeGoal />;
}
Output:
Example:
We can embed JavaScript expressions in JSX by using curly braces:
function Garage(props) {
return (
<>
<h1>Garage</h1>
</>
);
Example:
const cars = [];
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.
Example:
Return the MadeGoal component if isGoal is true, otherwise return the MissedGoal component:
function MissedGoal() {
return (
<div>
<h1>MISSED!</h1>
</div>
);
function MadeGoal() {
return (
<div>
<h1>Goal!</h1>
<MissedGoal />
</div>
);
const isGoal=false;
return (
<div>
</div>
Output:
React Lists
In React, you will render lists with some type of loop.
Example:
Let's render all of the cars from our garage:
function Car(props) {
return (
<div>
<ul>
</ul>
</div>
);
}
Output:
When you run this code in your create-react-app, it will work but you will receive a warning that there
is no "key" provided for the list items.
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.
Keys need to be unique to each sibling. But they can be duplicated globally.
Generally, the key should be a unique ID assigned to each item. As a last resort, you can use the array
index as a key.
Example:
Let's refactor our previous example to include keys:
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>
</>
);
}
Output:
React Events
Just 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:
React:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
Example:
Put the shoot function inside the Football component:
return (
);
}
Output:
Passing Arguments
To pass an argument to an event handler, use an arrow function.
Example:
Send " React Passing Event " as a parameter to the shoot function, using arrow function:
alert(a);
return (
);
Output:
Example:
Arrow Function: Sending the event object manually:
alert(b.type);
/*
*/
return (
);
Output: