Overview of JSX
Overview of JSX
Syntax of JSX
JSX looks very similar to HTML, but there are some important differences:
You can embed JavaScript expressions inside JSX by wrapping them in curly
braces {}.
This will render the text Hello, Alice!, with the JavaScript expression {name}
being evaluated and inserted into the output.
3. Attributes in JSX
In JSX, attributes are written in camelCase. For example, instead of class, you
use className, and instead of for, you use htmlFor.
4. JSX Children
In this example, the button has a click event handler, and its text (Click Me) is
passed as a child.
You can use JavaScript expressions such as ternary operators or logical && for
conditional rendering within JSX.
Or with &&:
JSX can render an array of elements, which is useful for dynamic lists.
Here, we are mapping over the items array and returning a list item for each
element.
7. JSX Fragment
If you need to return multiple elements without adding extra nodes to the DOM,
you can use React.Fragment or shorthand <>...</>.
const element = (
<>
<h1>Hello, World!</h1>
<p>This is a JSX fragment example.</p>
</>
);
Example:
Transpiling JSX
is transpiled into:
javascript
Copy code
const element = React.createElement('h1', null, 'Hello, World!');
This means that JSX gets converted into React.createElement() calls, which
React uses to create elements in the virtual DOM.
1. map() in JSX
The map() function is one of the most commonly used array methods in JSX. It
creates a new array by applying a function to each element in the original array.
In React, map() is often used to dynamically render lists of components or
elements.
Syntax:
Example:
function FruitList() {
const fruits = ['Apple', 'Banana', 'Cherry', 'Date'];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li> // Rendering each fruit as a list item
))}
</ul>
);
}
Explanation:
o We use the map() function to loop through the fruits array.
o For each item in the array, a <li> element is returned, which is
rendered in the <ul> element.
o The key={index} is added to each list item to help React identify
each element uniquely, which improves performance when
updating the list.
2. filter() in JSX
The filter() function creates a new array that contains only the elements that
satisfy a given condition. It’s useful for conditionally rendering items based on
specific criteria.
Syntax:
Use Case in JSX: Filter items based on a condition and render them.
Example:
return (
<ul>
{evenNumbers.map((number, index) => (
<li key={index}>{number}</li> // Rendering even numbers only
))}
</ul>
);
}
Explanation:
o The filter() method filters the numbers array to include only even
numbers (number % 2 === 0).
o The filtered array, evenNumbers, is then mapped over to render
each even number in a <li> element.
3. reduce() in JSX
Syntax:
const result = array.reduce(callback(accumulator, currentValue, index,
array) => {
return newAccumulator;
}, initialAccumulatorValue);
Example:
function TotalPrice() {
const prices = [10, 20, 30, 40, 50];
return (
<div>
<h1>Total Price: ${totalPrice}</h1>
</div>
);
}
Explanation:
o The reduce() function is used to sum up all the prices in the prices
array.
o total is the accumulator that starts at 0, and price is the current
element in the array. After each iteration, total is updated to include
the new price.
o The final result is displayed in the component.
You can combine these array methods in more complex scenarios to transform
and display data in your JSX components.
function CartSummary() {
const cartItems = [
{ id: 1, name: 'Apple', price: 10, quantity: 2 },
{ id: 2, name: 'Banana', price: 5, quantity: 5 },
{ id: 3, name: 'Orange', price: 8, quantity: 3 },
{ id: 4, name: 'Grapes', price: 20, quantity: 1 },
];
return (
<div>
<h1>Cart Summary</h1>
<ul>{itemList}</ul>
<h2>Total: ${totalPrice}</h2>
</div>
);
}
Explanation:
o Step 1: Use filter() to get only the items with a quantity greater
than 2.
o Step 2: Use map() to render each item in the filtered list, showing
the name, price, quantity, and total cost for each item.
o Step 3: Use reduce() to calculate the total price of the filtered
items.
Summary
Arrow functions are a concise way of writing functions. They use the => syntax
and have a few important differences compared to traditional function
expressions:
No this binding: Arrow functions don’t have their own this. They inherit
this from the parent scope (lexical scoping), which is useful in React
when handling events.
Concise syntax: Arrow functions are often used for single-expression
functions, making the code more compact and readable.
Implicit return: If the function body is a single expression, the return
keyword can be omitted.
Regular Function:
function add(a, b) {
return a + b;
}
Arrow Function:
javascript
Copy code
const add = (a, b) => a + b; // implicit return
1. Event Handlers
Arrow functions are often used to define event handlers in JSX. Using
arrow functions ensures that the this keyword inside the function refers to
the current instance of the React component.
Example:
function ClickCounter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={incrementCount}>Increase Count</button>
</div>
);
}
Explanation:
Arrow functions are also used directly inside JSX as inline event
handlers. This is especially useful for quick actions.
Example:
function Greeting() {
const [message, setMessage] = useState('Hello');
return (
<div>
<h1>{message}</h1>
<button onClick={() => setMessage('Hello, World!')}>Change
Message</button>
</div>
);
}
Explanation:
Arrow functions are often used within map() when rendering lists in JSX.
This is a common pattern when working with dynamic data.
Example:
function FruitList() {
const fruits = ['Apple', 'Banana', 'Orange'];
return (
<ul>
{fruits.map((fruit, index) => (
<li key={index}>{fruit}</li> // Arrow function inside map
))}
</ul>
);
}
Explanation:
Example:
function Parent() {
const [count, setCount] = useState(0);
Explanation:
Example:
function ToggleButton() {
const [isToggled, setIsToggled] = useState(false);
return (
<div>
<h1>{isToggled ? 'On' : 'Off'}</h1>
<button onClick={() => setIsToggled(!isToggled)}>
Toggle
</button>
</div>
);
}
Explanation:
Important Considerations
General Syntax:
If the function has multiple parameters, you can still define it concisely:
For functions that only return a single expression, you can omit the return
keyword:
In React, arrow functions (lambda expressions) are extremely useful for writing
event handlers, inline functions, and rendering dynamic lists. They are typically
used when:
You need a function in JSX for event handling (e.g., onClick, onChange).
You need to define small functions to map, filter, or reduce arrays in JSX
rendering.
You need to pass functions as props.
Arrow functions are commonly used in JSX to handle events because they
preserve the this context of the surrounding scope (the React component).
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increase Count</button>
</div>
);
}
function FruitList() {
const fruits = ['Apple', 'Banana', 'Cherry'];
return (
<ul>
{fruits.map(fruit => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
Explanation:
o The map() method uses an arrow function fruit => <li
key={fruit}>{fruit}</li> to generate each list item from the fruits
array.
function Parent() {
const [message, setMessage] = useState("Hello!");
return (
<div>
<h1>{message}</h1>
<Button onClick={handleClick} />
</div>
);
}
function Toggle() {
const [isToggled, setIsToggled] = useState(false);
return (
<div>
<h1>{isToggled ? "On" : "Off"}</h1>
<button onClick={() => setIsToggled(!isToggled)}>
Toggle
</button>
</div>
);
}
Explanation:
o The arrow function () => setIsToggled(!isToggled) is used to
toggle the state between true and false.
o The conditional rendering (isToggled ? "On" : "Off") displays the
current state.
A specific implementation of
A general programming concept
Concept lambda expressions in
(e.g., in Python, Java, C#).
JavaScript (introduced in ES6).
Object their own arguments object. They inherit it from the parent
scope.
REST is not a protocol but an architectural style, which means it outlines a set
of guidelines that a system should follow to be considered RESTful.
1. Statelessness:
o Every request from a client to a server must contain all the
information the server needs to fulfill the request. The server does
not store any information about the client between requests.
o Each request is independent and isolated, meaning there is no
session or memory of previous requests.
o This makes RESTful services scalable and easier to maintain.
Example: If a client wants to fetch user data, the request should include
all necessary parameters (e.g., authentication tokens) since the server
does not retain any information about previous requests.
2. Client-Server Architecture:
o REST architecture follows a client-server model, where the client
is responsible for the user interface and user experience, while the
server is responsible for processing the requests, managing
resources, and handling business logic.
o Clients and servers can evolve independently, as long as the
communication between them is maintained according to the REST
constraints.
3. Uniform Interface:
o REST requires that the interface between the client and server is
consistent and uniform, ensuring that resources are identifiable and
accessible in the same way regardless of which resource or service
is being interacted with.
o This makes it easier for developers to work with multiple RESTful
services, as the structure remains the same.
1. GET (Retrieve):
o Used to retrieve data from the server. It is a safe and idempotent
method, meaning that it does not modify any data on the server and
can be called multiple times without changing the state of the
resource.
o Example: GET /users/123 to fetch user with ID 123.
2. POST (Create):
o Used to create a new resource on the server. The request body
typically contains the data to be created.
o Example: POST /users to create a new user. The request body
might contain { "name": "John Doe", "email":
"[email protected]" }.
3. PUT (Update):
o Used to update an existing resource. The request body contains the
updated data for the resource. PUT is idempotent, meaning that
calling it multiple times will not result in different outcomes.
o Example: PUT /users/123 to update the user with ID 123.
4. DELETE (Delete):
o Used to delete a resource on the server.
o Example: DELETE /users/123 to delete the user with ID 123.
5. PATCH (Partial Update):
o Used to apply a partial update to a resource. Unlike PUT, which
replaces the entire resource, PATCH only modifies the parts of the
resource that are specified in the request body.
o Example: PATCH /users/123 to update some fields of the user
with ID 123, like their email or phone number.
In REST, resources are the core concept, and each resource is identified by a
URI (Uniform Resource Identifier) or URL (Uniform Resource Locator). A
resource could be a user, a product, a blog post, etc.
HTTP
URL Action Example Request Body Description
Method
Fetch
Returns a list
GET /users all -
of all users.
users
Fetch a Returns
GET /users/{userId} single - details of a
user user with a
HTTP
URL Action Example Request Body Description
Method
specific
userId.
Creates a
Create new user
{ "name": "Alice", "email":
POST /users a new with the
"[email protected]" }
user provided
data.
{ "name": "Alice Updated",
Update Updates the
"email":
PUT /users/{userId} user user with the
"[email protected]"
details given userId.
}
Deletes the
Delete
DELETE /users/{userId} - user with the
a user
given userId.