Module 3: Functional Components

Now we get to the core concept of React: components. Think of them as custom, reusable HTML tags that you create.

1. What is a Component? đź§©

A component is an independent, reusable piece of UI. It’s like a JavaScript function that returns a chunk of JSX. The main idea is to break down your entire user interface into smaller, manageable pieces.

For example, a typical webpage could be broken down into components like `

`, ``, `
`, and `
`. Each component manages its own structure and logic, making your code much easier to understand and maintain.

Analogy: Think of components as Lego bricks. You can build small, simple bricks, and then combine them to create complex structures.

2. Creating Your First Component

The simplest way to create a React component is to write a JavaScript function. This is called a functional component.

A valid functional component:

  • Is a standard JavaScript function.
  • Its name must start with a capital letter (e.g., `MyComponent`, not `myComponent`). This is how React distinguishes components from regular HTML tags.
  • It returns JSX that describes the UI.

Let's create a `Greeting` component:


// This is a functional component
function Greeting() {
  return <h1>Welcome to my app!</h1>;
}

3. Composing and Rendering Components

Once you have a component, you can use it just like a regular HTML tag. The real power of React comes from composing components—placing components inside other components.

Let's create a main `App` component that uses our `Greeting` component. Then, we'll render the `App` component to the DOM.


// 1. Define a simple component
function Greeting() {
  return <h1>Welcome to my app!</h1>;
}

// 2. Define a main App component that USES the Greeting component
function App() {
  return (
    <div>
      <Greeting />
      <p>This is the main application content.</p>
    </div>
  );
}

// 3. Render the main App component to the root div
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

In this example, `` is used inside `App`. This is called composition. By building small, focused components and composing them together, you can create complex UIs from simple, manageable parts.