React Js
Introduction
What Can JavaScript Do?
• JavaScript is the programming language of the web.
• It can calculate, manipulate and validate data.
• It can update and change both HTML and CSS.
JavaScript Syntax
JavaScript Values
The JavaScript syntax defines two types of values:
• Literals (Fixed values)
• Variables (Variable values)
JavaScript Literals
• The most important syntax rules for literals (fixed values) are:
• Numbers are written with or without decimals:
Syntax-
The most important syntax rules for literals (fixed values) are:
Numbers are written with or without decimals:
<script>
[Link]("demo").innerHTML = 10.50;
</script>
• Strings are text, written within double or single quotes:
<script>
[Link]("demo").innerHTML = 'John Doe';
</script>
Syntax-
JavaScript Variables-
Variables are containers for storing data values.
Variables must be identified with unique names.
Example
• Define x as a variable
let x;
• Assign the value 6 to x
x = 6;
Example -
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Syntax</h1>
<h3>The let and const keywords create variables</h3>
<p id="demo"></p>
<script>
let x = 5;
const fname = "John";
[Link]("demo").innerHTML = fname + " is " + x + " years old.";
</script>
</body>
</html>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
[Link]("demo").innerHTML = "The value of z is " + z;
</script>
JavaScript Functions and Events -
•A JavaScript function is a block of JavaScript code, that can be executed when "called" for.
•For example, a function can be called when an event occurs, like when the user clicks a button.
JavaScript in <head> or <body> -
•You can place any number of scripts in an HTML document.
•Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
External JavaScript -
• Scripts can also be placed in external files:
• External file: [Link]
function myFunction() {
[Link]("demo").innerHTML = "Paragraph changed.";
• External scripts are practical when the same code is used in many different web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source) attribute of a <script>
tag:
JavaScript Variables
1. JavaScript variables are containers for data.
2. JavaScript variables can be declared in 4 ways:
Modern JavaScript
Using let
Using const
Older JavaScript
1. Using var (Not Recommended)
2. Automatically (Not Recommended)
Difference between var, let and const
keywords
JavaScript provides three ways to declare variables: var, let, and const, but they differ in scope, hoisting
behaviour, and re-assignment rules.
[Link]:
Declares variables with function or global scope and allows re-declaration and updates within the same
scope.
[Link]:
Declares variables with block scope, allowing updates but not re-declaration within the same block.
[Link]:
Declares block-scoped variables that cannot be reassigned after their initial assignment.
Example -
// var example
var x = 10;
var x = 20; // Re-declaration allowed
x = 30; // Update allowed
[Link](x); // Output: 30
// let example
let y = 10;
// let y = 20; // Re-declaration NOT allowed
y = 25; // Update allowed
[Link](y); // Output: 25
Example -
// const example
const z = 10;
// z = 20; // Re-assignment NOT allowed
React with Vite
Open your terminal (Command Prompt, PowerShell, or Bash).
1. Run the project creation command:
2. Enter the following command to start the interactive setup process. You can use npm, yarn, pnpm,
or bun:
npm create vite@latest
Follow the prompts:
1. The CLI will guide you through configuration:
2. Project name: Enter a name for your project (e.g., my-react-app).
3. Select a framework: Use your arrow keys to select React.
4. Select a variant: Choose your preferred language variant (e.g., TypeScript, JavaScript, TypeScript +
SWC, or JavaScript + SWC).
5. Navigate to your project directory:
6. Once the scaffolding is complete, change into the new directory:
React with Vite
cd my-react-app
(Replace my-react-app with the name you chose)
Install dependencies:
Install all the required packages listed in the [Link] file:
npm install
1. Start the development server:
2. Run the command to launch the local development server:
npm run dev
Vite will start the server, and your terminal will display a local address, typically [Link]
Open this URL in your web browser to see your new React application.
How to start modify Code
PS C:\Users\adity> cd my-react-app
PS C:\Users\adity\my-react-app> npm install
up to date, audited 161 packages in 4s
36 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
PS C:\Users\adity\my-react-app> npm run dev
> my-react-app@0.0.0 dev
> vite
Modify the React App
Look in the my-react-app directory, and you will find a src folder. Inside the src folder there is a file
called [Link], open it and it will look like this:
ExampleGet your own [Link] Server
This is the default content of the [Link] file in the src folder:
Modify the React App
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
}
export default App;
See the changes in the browser when you click Save.
Rendering HTML
Definition -
Rendering HTML is the process by which a web browser reads HTML code and displays it as a visible
web page on the screen.
How HTML Rendering Works -
• The browser loads the HTML file
• It parses the HTML tags
• Creates a DOM (Document Object Model)
• The content is rendered visually (text, images, buttons, etc.)
React renders HTML to the web page via a container, and a function called createRoot().
The Container
React uses a container to render HTML in a web page.
Typically, this container is a <div id="root"></div> element in the [Link] file.
If you have followed the steps in the previous chapter, you should have a file called [Link] in the
root directory of your project:
ExampleGet your own [Link] Server
The default content of the [Link] file:
<html lang="en">
<body>
<div id="root"></div>
<script type="module" src="/src/[Link]"></script>
</body>
</html>
The createRoot Function -
The createRoot function is located in the [Link] file in the src folder, and is a built-in function that is
used to create a root node for a React application.
Example
The default content of the src/[Link] file:
Example -
import { createRoot } from 'react-dom/client'
createRoot([Link]('root')).render(
<h1>Hello React!</h1>
)
React Components Functional vs Class Components
1. What are React Components?
In React, components are reusable pieces of code that represent parts of a UI. Each component is a
JavaScript function or class that renders a section of the UI based on the properties (props) it
receives. Components make the code modular, maintainable, and easier to debug.
1. Functional Components: A simple function that returns JSX (JavaScript XML).
2. Class Components: A JavaScript ES6 class that extends [Link] and returns JSX in its
render() method.
2. Functional Components
Functional components are plain JavaScript functions that return JSX. They are simpler to write and
understand, making them a popular choice among developers, especially after the introduction of React
Hooks, which allow state and lifecycle features in functional components.
Syntax and Structure -
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
}
export default App;
Advantages of Functional Components
• Simplicity: Functional components are shorter and more concise.
• Performance: Functional components are generally faster since they lack lifecycle methods and
state handling complexity.
• Ease of Testing: Functions are easier to test, which makes testing functional components
straightforward.
• React Hooks Support: With Hooks, functional components can manage state and lifecycle
methods, bridging the gap between functional and class components.
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};export default Counter;
3. Class Components
class components were the primary way to manage state and lifecycle in React. Class
components are JavaScript ES6 classes that extend from [Link] and use the
render() method to return JSX.
Syntax and Structure -
import React, { Component } from 'react';
class Greeting extends Component {
render() {
return <h1>Hello, {[Link]}!</h1>;
export default Greeting;
Advantages of Class Components-
Lifecycle Methods: Class components have access to a wide range of lifecycle methods
like componentDidMount, componentDidUpdate, and componentWillUnmount.
Readability for Complex Logic: For some, class components are easier to organize and
read when dealing with more complex logic, as everything is inside a single class
structure.
Difference between Functional and Class Components -
Types of React Hooks -
React provides a range of hooks that enable functional components to manage state, side
effects, and other core behaviors. Some of the most commonly used React hooks include:
1. State Hooks
State hooks like useState and useReducer enable functional components to manage state
in a clean, efficient, and modular way.
a. useState: The useState hook is used to declare state variables in functional
components. It allows us to read and update the state within the component.
Example -
import React, { useState } from "react";
function App() {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div>
<h1>Count: {count}</h1> {/* Display the current count */}
<button onClick={increment}>Increment</button> {/* Increment the count */}
<button onClick={decrement}>Decrement</button> {/* Decrement the count */}
</div>
);
}
Uses of useState - useState is used to declare state variables in functional components.
• The state variable (count) and the updater function (setCount) allow you to read and
update the state.
• const [state, setState] = useState(initialState);
• state: The current value of the state.
• setState: A function used to update the state.
• initialState: The initial value of the state, which can be a primitive type or an
object/array
useReducer -
The useReducer hook is a more advanced state management hook used for handling
more complex state logic, often involving multiple sub-values or more intricate state
transitions.
import React, { useReducer } from "react";
function reducer(count, action) {
if (action === "increment") {
return count + 1;
}
if (action === "decrement") {
return count - 1;
return count;
}
function App() {
const [count, dispatch] = useReducer(reducer, 0);
const increment = () => dispatch("increment");
const decrement = () => dispatch("decrement");
return (
<div>
<h1>Count: {count}</h1> {/* Display the current count */}
<button onClick={increment}>Increment</button> {/* Increment the count */}
<button onClick={decrement}>Decrement</button> {/* Decrement the count */}
</div>
);
} export default App;
Props in React -
• Props (Properties) are used to pass data from one component to another.
• Props are passed to components via HTML attributes.
• Props are read-only
• They help make components reusable
• Data flows Parent → Child
Props in React with example-
Without props:
function Car() {
return <h2>I am a Red Car</h2>;
This component is fixed.
Props in React with example-
With props:
function Car(props) {
return <h2>I am a {[Link]} Car</h2>;
<Car color="Red" />
<Car color="Blue" />
<Car color="Black" />
Props Basic syntax -
Basic Syntax of Props -
Parent Component -
<Car brand="Toyota" />
Child Component-
function Car(props) {
return <h2>I am a {[Link]}</h2>;
}
Props Basic syntax -
function Car(props) {
return (
<div>
<h2>Car Brand: {[Link]}</h2>
<h3>Color: {[Link]}</h3>
<h3>Price: {[Link]}</h3>
</div>
);
}
Props Basic syntax -
function App() {
return (
<div>
<Car brand="Toyota" color="Red" price="10 Lakhs" />
<Car brand="BMW" color="Black" price="50 Lakhs" />
</div>
);
}
export default App;
Props Using Destructuring
function Car(props) {
const {brand, model} = props;
return (
<h2>I love my {brand} {model}!</h2>
);
}
createRoot([Link]('root')).render(
<Car brand="Ford" model="Mustang" color="red" year={1969} />
);
•
States in React Js
ReactJS State is a built-in object used to store and manage data that changes over time in a
component.
• It allows React components to respond dynamically to user actions and application events.
• State is mutable and can be updated using setState or the useState hook.
• When state changes, React automatically re-renders the component.
• State helps control dynamic content like form inputs, UI toggles, and fetched data.
• Syntax:
• const [state, setState] = useState(initialState);
States in React Js
• state: The current state value.
• setState: A function that is used to update the state.
• initialState: The initial value that the state will hold when the component is first rendered.
Creating State Object -
• Creating a state in React is essential to building dynamic and interactive components. We
can create a state object within the constructor of the class component.
Example -
import React from 'react';
class MyComponent extends [Link] {
constructor(props) {
super(props);
[Link] = {
brand: 'Ford', // Example property in the state
};
}
render() {
return (
<div>
<h1>My Car</h1>
{/* Other component content */}
</div>
);
}
}
Example -
The MyComponent class extends [Link], and inside the constructor, it initializes
the component's state with a brand property set to 'Ford'.
The render() method returns JSX that displays an <h1> heading with the text "My Car" and
renders the component's content.
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:
• onClick instead of onclick.
• React event handlers are written inside curly braces:
• onClick={shoot} instead of onclick="shoot()".
React Events Example
import { createRoot } from 'react-dom/client'
function Football() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
createRoot([Link]('root')).render(
<Football />
);
React Events Example(Passing Arguments)
Note - Send "Goal!" as a parameter to the shoot function, using arrow function:-
import { createRoot } from 'react-dom/client'
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
createRoot([Link]('root')).render(
<Football />
);
React Event Object
Event handlers have access to the React event that triggered the function.
In our example the event is the "click" event.
Example:
Arrow Function: Sending the event object manually:
React Event Object
import { createRoot } from 'react-dom/client’
function Football() {
const shoot = (a, b) => {
alert([Link]);
/*
'b' represents the React event that triggered the function,
in this case the 'click' event
*/
}
return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}
createRoot([Link]('root')).render(
<Football />
);
React Event Object(Simple Mouse Hover)
import { useState } from "react";
function HoverExample() {
const [message, setMessage] = useState("");
return (
<div>
<h2
onMouseEnter={() => setMessage("Mouse is over the text!")}
onMouseLeave={() => setMessage("Mouse left the text!")}
>
Hover over me
</h2>
<p>{message}</p>
</div>
);
}
export default HoverExample;
Hover Effect (Change Color Example)
import { useState } from "react";
function HoverColor() {
const [isHover, setIsHover] = useState(false);
return (
<button
onMouseEnter={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
style={{
backgroundColor: isHover ? "blue" : "gray",
color: "white",
padding: "10px 20px",
border: "none"
}}
>
Hover Me
</button>
);
}
export default HoverColor;
React Forms
Just like in HTML, React uses forms to allow users to interact with the web page.
Adding Forms in React
You add a form with React like any other element:
React Forms
import { createRoot } from 'react-dom/client'
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
createRoot([Link]('root')).render(
<MyForm />
);
React Hooks -
React Hooks, introduced in React 16.8, enable functional components to use state,
lifecycle, and other React features without relying on class components.
• Eliminate the need for class components for state and side-effect management.
• Improve code readability and encourage a functional programming style.
• Widely adopted in modern React projects for cleaner and more maintainable code.