Lifecycle Methods (Class Components)
Learn about React component lifecycle methods such as `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount`, and how to use them to manage side effects.
Mastering React.js: Build Modern Web Applications
JSX and Components
React utilizes JSX (JavaScript XML) to define the structure and content of UI elements. Components are the building blocks of a React application. They are reusable, independent pieces of code that render a specific part of the user interface. Combining JSX and components enables a declarative and modular approach to building complex UIs.
What is JSX?
JSX is a syntax extension to JavaScript that allows you to write HTML-like structures directly within your JavaScript code. It's not actually HTML, but it gets transformed into standard JavaScript calls that create React elements.
Benefits of using JSX:
- Readability: JSX resembles HTML, making it easier to understand the UI structure.
- Maintainability: JSX code is easier to maintain and modify compared to complex JavaScript DOM manipulation.
- Safety: JSX helps prevent injection attacks as it automatically escapes values embedded in the markup.
Example of JSX:
const element = <h1>Hello, React!</h1>;
What are React Components?
Components are independent and reusable pieces of code. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen. Think of them as custom HTML elements that you create and reuse throughout your application.
Key characteristics of React components:
- Reusability: Components can be used multiple times in different parts of your application.
- Composability: Components can be composed together to create more complex UIs.
- Maintainability: Smaller, independent components are easier to maintain and debug.
Understanding JSX Syntax
JSX syntax builds upon standard HTML with some important JavaScript integration points:
Embedding Expressions
You can embed JavaScript expressions within JSX using curly braces {}
. This is a powerful way to dynamically render content based on variables, calculations, or conditions.
Example:
const name = 'Alice';
const element = <h1>Hello, {name}!</h1>;
JSX Attributes
JSX attributes work similarly to HTML attributes, but with some key differences. Attribute names follow a camelCase convention (e.g., className
instead of class
, onClick
instead of onclick
). You can also pass JavaScript expressions as attribute values using curly braces.
Example:
const imageUrl = 'https://example.com/image.jpg';
const element = <img src={imageUrl} alt="Example Image" />;
Conditional Rendering
You can use JavaScript's conditional operators (ternary operator or &&
operator) within JSX to conditionally render content.
Example using the ternary operator:
const isLoggedIn = true;
const element = (
<div>
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
</div>
);
Example using the &&
operator (short-circuit evaluation):
const showMessage = true;
const element = (
<div>
{showMessage && <p>This message is visible!</p>}
</div>
);
JSX Must Have One Root Element
In JSX, you must always return a single root element. If you need to return multiple elements, you can wrap them in a parent element like a <div>
, a <section>
, or use a React Fragment (<></>
).
Example using a React Fragment:
const element = (
<>
<h1>Title</h1>
<p>Paragraph</p>
<>
);
Creating Reusable React Components
React components come in two main flavors: Functional Components and Class Components. Functional components are simpler and often preferred for presentational logic, while class components offer more advanced features like state management and lifecycle methods.
Functional Components
Functional components are JavaScript functions that accept props as an argument and return JSX. They are typically used for simple UI elements that primarily display data.
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage
const element = <Greeting name="Bob" />;
Using Arrow Functions (Concise Syntax):
const Greeting = (props) => <h1>Hello, {props.name}!</h1>;
// Usage
const element = <Greeting name="Eve" />;
Class Components
Class components are JavaScript classes that extend the React.Component
class. They have access to state (local data that can change over time) and lifecycle methods (methods that are called at specific points in a component's life cycle). Class components are used when you need more control over component behavior or state.
Example:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
// Usage
const element = <Counter />;
Props
Props (short for "properties") are a way to pass data from a parent component to a child component. They are read-only from the child component's perspective. Props allow you to customize and configure components.
Example demonstrating props passing:
function Card(props) {
return (
<div className="card">
<h2>{props.title}</h2>
<p>{props.description}</p>
</div>
);
}
// Usage
const cardElement = <Card title="My Card" description="This is a sample card." />;
State
State is a component's internal data. It represents data that can change over time, causing the component to re-render. State is primarily used in class components (using this.state
and this.setState
) and functional components using the useState
Hook.
Example using the useState
Hook in a functional component:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// Usage
const element = <Counter />;