Unit-5: "React JS"
Module-5
Chapter 3
React JS
Introduction
[Link] is a popular open-source JavaScript library used for building user interfaces,
particularly for single-page applications. Developed by Facebook, React allows developers to
create dynamic and interactive UI components that efficiently update in response to user
interactions or changes in data.
The various feature of React Js are
• Component-Based: React follows a component-based architecture, where the UI is
divided into reusable and independent components.
• Virtual DOM: React uses a virtual DOM to efficiently update the UI, resulting in
better performance by minimizing DOM manipulation.
• JSX: JSX allows developers to write HTML-like code within JavaScript, making it
easier to describe UI components.
• Unidirectional Data Flow: React follows a unidirectional data flow, where data flows
from parent to child components, simplifying state management.
• Declarative Syntax: React promotes a declarative programming style, allowing
developers to describe the UI based on state, rather than imperatively manipulating
the DOM.
• Lifecycle Methods: React components have lifecycle methods that allow developers
to hook into different stages of a component's life, such as mounting, updating, and
unmounting.
• Hooks: React Hooks provide a way to use state and other React features in functional
components, improving code readability and reusability.
• Server-Side Rendering (SSR): React supports server-side rendering, enhancing initial
page load performance and SEO.
• Large Ecosystem: React has a vast ecosystem with numerous libraries, tools, and
community support, making it a popular choice for building web and mobile
applications.
• Community: React has a large and active community that contributes to its growth
and provides resources, tutorials, and support for developers.
• React, sometimes referred to as a frontend JavaScript framework, is a JavaScript
library created by Facebook.
[Link] History
❖ React is a tool for building UI components.
❖ Current version of [Link] is V18.0.0 (April 2022).
❖ Initial Release to the Public (V0.3.0) was in July 2013.
Dept of CSE,GST,Bengaluru Page 1
Unit-5: "React JS"
❖ [Link] was first used in 2011 for Facebook's Newsfeed feature.
❖ Facebook Software Engineer, Jordan Walke, created it.
❖ Current version of create-react-app is v5.0.1 (April 2022).
❖ create-react-app includes built tools such as webpack, Babel, and ESLint
5.3.1Components:
In React, UIs are composed of reusable pieces called components. A component is a
self-contained module that encapsulates a part of the user interface and its behavior.
Components can be nested within each other to create complex UIs.
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
Types of Components
a) Functional Components: These are JavaScript functions that take props (properties) as
an argument and return React elements. They are also called stateless components
because they don't manage state.
b) Class Components: These are ES6 classes that extend from [Link]. They
have a render() method that returns a React element. Class components can manage
state and have additional features like lifecycle methods.
a)Class Component
A class component must include the extends [Link] statement. This statement
creates an inheritance to [Link], and gives your component access to React.
Component's functions.
The component also requires a render() method, this method returns HTML.
ExampleGet your own [Link] Server
Create a Class component called Car
class Car extends [Link] {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Component Constructor
❖ If there is a constructor () function in your component, this function will be called
when the component gets initiated.
❖ The constructor function is where you initiate the component's properties.
❖ In React, component properties should be kept in an object called state.
Dept of CSE,GST,Bengaluru Page 2
Unit-5: "React JS"
Example
Create a constructor function in the Car component, and add a color property:
import React from 'react';
import ReactDOM from 'react-dom/client';
class Car extends [Link] {
constructor() {
super();
[Link] = {color: "red"};
}
render() {
return <h2>I am a {[Link]} Car!</h2>;
}
}
const root = [Link]([Link]('root'));
[Link](<Car />);
b)Function Component
A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier to
understand, and will be preferred
Create a Function component called Car
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
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
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
const root = [Link]([Link]('root'));
[Link](<Car />);
Dept of CSE,GST,Bengaluru Page 3
Unit-5: "React JS"
React Props
❖ Props are arguments passed into React components.
❖ Props are passed to components via HTML attributes.
❖ React Props are like function arguments in JavaScript and attributes in HTML.
Example
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car(props) {
return <h2>I am a { [Link] }!</h2>;
}
const myElement = <Car brand="Ford" />;
const root = [Link]([Link]('root'));
[Link](myElement);
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 <h2>I am a { [Link] }!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
const root = [Link]([Link]('root'));
[Link](<Garage />);
Props as variable
If you have a variable to send, and not a string as in the example above, you just put the
variable name inside curly brackets:
Dept of CSE,GST,Bengaluru Page 4
Unit-5: "React JS"
Example
import React from 'react';
import ReactDOM from 'react-dom/client';
function Car(props) {
return <h2>I am a { [Link] }!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
const root = [Link]([Link]('root'));
[Link](<Garage />);
5.3.2 Styling in CSS
There are many ways to style React with CSS, this tutorial will take a closer look at three
common ways:
❖ Inline styling
❖ CSS stylesheets
❖ CSS Modules
a) Inline Styling: You can apply styles directly to JSX elements using the style attribute. This
is done by passing a JavaScript object where keys are camelCased CSS properties and values
are the desired styles.
Example:
import React from 'react';
import ReactDOM from 'react-dom/client';
const Header = () => {
return (
<>
<h1 style={{color: "red"}}>Hello Style!</h1>
<p>Add a little style!</p>
</>
);
}
const root = [Link]([Link]('root'));
[Link](<Header />);
Dept of CSE,GST,Bengaluru Page 5
Unit-5: "React JS"
b) CSS Modules: CSS Modules allow you to write CSS files that are scoped locally to the
component they belong to. This means you can use regular CSS syntax and import styles
directly into your component files.
// [Link]
import React from 'react';
import styles from './[Link]';
const MyComponent = () => {
return <div className={[Link]}>Hello, World!</div>;
};
export default MyComponent;
/* [Link] */
.container {
color: blue;
font-size: 20px;
}
c) CSS Modules:
❖ Another way of adding styles to your application is to use CSS Modules.
❖ CSS Modules are convenient for components that are placed in separate files
Example
Create a new file called "[Link]" and insert some CSS code in it:
[Link]:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
}
Import the stylesheet in your component:
[Link]:
import styles from './[Link]';
const Car = () => {
return <h1 className={[Link]}>Hello Car!</h1>;
}
export default Car;
Import the component in your application:
[Link]:
import ReactDOM from 'react-dom/client';
import Car from './[Link]';
const root = [Link]([Link]('root'));
Dept of CSE,GST,Bengaluru Page 6
Unit-5: "React JS"
[Link](<Car />);
5.3.3 React Forms
❖ In HTML, form data is usually handled by the DOM.
❖ In React, form data is usually handled by the components.
❖ When the data is handled by the components, all the data is stored in the component
state.
❖ You can control changes by adding event handlers in the onChange attribute.
❖ We can use the use State Hook to keep track of each inputs value and provide a
"single source of truth" for the entire application.
Example:
import { useState } from "react";
import ReactDOM from 'react-dom/client';
function MyForm() {
const [name, setName] = useState("");
return (
<form>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName([Link])}
/>
</label>
</form>
)
}
const root = [Link]([Link]('root'));
[Link](<MyForm />);
Submitting Forms
You can control the submit action by adding an event handler in the onSubmit attribute for
the <form>:
Dept of CSE,GST,Bengaluru Page 7
Unit-5: "React JS"
import { useState } from "react";
import ReactDOM from 'react-dom/client';
function MyForm() {
const [name, setName] = useState("");
const handleSubmit = (event) => {
[Link]();
alert(`The name you entered was: ${name}`);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName([Link])}
/>
</label>
<input type="submit" />
</form>
)
}
const root = [Link]([Link]('root'));
[Link](<MyForm />);
Multiple Input Fields
• You can control the values of more than one input field by adding a name attribute to
each element.
• We will initialize our state with an empty object.
• To access the fields in the event handler use the [Link] and
[Link] syntax.
Dept of CSE,GST,Bengaluru Page 8
Unit-5: "React JS"
• To update the state, use square brackets [bracket notation] around the property name.
Example:
import { useState } from "react";
import ReactDOM from "react-dom/client";
function MyForm() {
const [inputs, setInputs] = useState({});
const handleChange = (event) => {
const name = [Link];
const value = [Link];
setInputs(values => ({...values, [name]: value}))
}
const handleSubmit = (event) => {
[Link]();
[Link](inputs);
}
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
name="username"
value={[Link] || ""}
onChange={handleChange}
/>
</label>
<label>Enter your age:
<input type="number" name="age" value={[Link] || ""}
onChange={handleChange}/>
</label>
<input type="submit" />
</form>
)
}
Dept of CSE,GST,Bengaluru Page 9
Unit-5: "React JS"
Text area
✓ The textarea element in React is slightly different from ordinary HTML.
✓ In HTML the value of a textarea was the text between the start tag <textarea> and the
end tag </textarea>.
<textarea>
Content of the textarea.
</textarea>
Example:
A simple textarea with some content:
import { useState } from 'react';
import ReactDOM from 'react-dom/client';
function MyForm() {
const [textarea, setTextarea] = useState(
"The content of a textarea goes in the value attribute"
);
const handleChange = (event) => {
setTextarea([Link])
}
return (
<form>
<textarea value={textarea} onChange={handleChange} />
</form>
)
}
const root = [Link]([Link]('root'));
[Link](<MyForm />);
Dept of CSE,GST,Bengaluru Page 10
Unit-5: "React JS"
Select
✓ A drop down list, or a select box, in React is also a bit different from HTML.
✓ In HTML, the selected value in the drop down list was defined with the selected
attribute:
<select>
<option value="Ford">Ford</option>
<option value="Volvo" selected>Volvo</option>
<option value="Fiat">Fiat</option>
</select>
Example
import { useState } from "react";
import ReactDOM from "react-dom/client";
function MyForm() {
const [myCar, setMyCar] = useState("Volvo");
const handleChange = (event) => {
setMyCar([Link])
}
return (
<form>
<select value={myCar} onChange={handleChange}>
<option value="Ford">Ford</option>
<option value="Volvo">Volvo</option>
<option value="Fiat">Fiat</option>
</select>
</form>
)
Dept of CSE,GST,Bengaluru Page 11
Unit-5: "React JS"
}
const root = [Link]([Link]('root'));
[Link](<MyForm />);
5.3.4 Building and Deployment
The general procedure for building and deploying a [Link] application:
[Link] Up Your Development Environment:
Install [Link] and npm (Node Package Manager) if you haven't already. You can download
them from the official [Link] website.
Install a code editor like Visual Studio Code, Sublime Text, or Atom.
[Link] a New React Project:
Use Create React App, a tool provided by Facebook, to quickly set up a new React project.
Run the following command in your terminal:
npx create-react-app my-react-app
[Link] to Your Project:
Once the project is created, navigate to its directory:
cd my-react-app
[Link] Your Application:
Start your development server by running:
npm start
This command will start a development server and open your React application in your
default web browser. You can now begin developing your application in the src directory.
[Link] Your Application for Production:
Once you're ready to deploy your application, you need to build it for production. Run the
following command:
npm run build
This command will create an optimized build of your application in the build directory.
Dept of CSE,GST,Bengaluru Page 12
Unit-5: "React JS"
[Link] a Hosting Provider:
Select a hosting provider for your React application. Popular options include Netlify, Vercel,
AWS, Firebase, Heroku, GitHub Pages, and others.
[Link] Your Application:
Deploy your application to the hosting provider of your choice.
The process may vary depending on the provider you've chosen.
Typically, you will upload your build files to the hosting server or connect your repository to
the hosting service for automatic deployments.
[Link] Your Deployed Application:
Once your application is deployed, test it thoroughly to ensure everything is working as
expected in a production environment.
[Link] and Maintain Your Application:
Monitor your deployed application for any issues or performance bottlenecks. Update
dependencies regularly and make improvements as needed.
Dept of CSE,GST,Bengaluru Page 13