Sage-Code Laboratory
index<--

Chapter 3: Building Blocks

In Chapter 3, we'll delve into the heart of React applications: components! Components are reusable UI building blocks that encapsulate data (state or props) and behavior (rendering logic). They serve as the foundation for creating complex and maintainable UIs.

Creating Your First React Component

Let's get started by building our first React component! Here's a simple example that displays a greeting message:


function Greeting() {
    return (
        <div>
            <h1>Hello, World!</h1>
        </div>
    );
}

This code defines a function named "Greeting" that returns JSX code. The JSX code defines a "div" element containing an "h1" element with the text "Hello, World!". This component can be reused throughout your application to display the greeting message.

Using JSX Syntax for Writing Components

JSX (JavaScript XML) is a syntax extension that allows you to write component code resembling HTML. It improves readability by combining the familiarity of HTML with the power of JavaScript. Within JSX, you write HTML-like tags that represent UI elements, and you can embed JavaScript expressions within those tags using curly braces ("{}").

Here are some key points about JSX:

Component Properties (Props)

Components often need to receive data from other components to customize their behavior and appearance. This data is passed down through properties (props). Props are read-only values that a component receives from its parent component.

Let's modify the "Greeting" component to accept a name as a prop:


function Greeting(props) {
    return (
        <div>
            <h1>Hello, {props.name}!</h1>
        </div>
    );
}

In this example, the "Greeting" component now takes a single prop named "name". Inside the JSX, we use curly braces to access the "name" prop and dynamically render the greeting message with the provided name.

Passing values to props

Props are like arguments passed to a function, but instead of being passed during the function call, they are provided when the component is used. Here's a breakdown of how props work in your example:

1. Defining the Component with Props:

2. Accessing Props within the Component:

3. Calling (or Using) the Component:


     <Greeting name="Alice" />  // Pass "Alice" as the value for the "name" prop

4. Rendering the Message:

Inside the Greeting component, you access props.name to retrieve the value ("Alice" in this case) and display it within the <h1> element.

Key Points:

Props are passed when the component is used, not called directly. Use dot notation ("props.name") to access data from props within the component.

We'll explore using components and props in more detail in the following chapters, along with advanced concepts like state management and lifecycle methods. Stay tuned!


Homepage: Rendering Components