Components in React

Components are the building blocks of a React application. They allow you to split the UI into independent, reusable pieces that can be managed and updated separately.

Why Use Components?

Using components helps to:

  • Organize your code by separating concerns.
  • Reuse code efficiently across your application.
  • Improve readability and maintainability of your codebase.

Rules of Components

  1. Component Naming: Component names should be written in CapitalCase.
  2. File Extension: Component files should use the .jsx extension.
  3. Importing Components: Always import a component before using it in another component.

Functional Components

Functional components are simple JavaScript functions that return JSX. They are the most common type of component in React.

Creating a Header Component

Let's create a Header.jsx component:

import React from "react";

const Header = () => {
    return (
        <>
            <h1>React App</h1>
        </>
    );
};

export default Header;

Importing the Header Component in App.jsx

Next, import the Header.jsx component in App.jsx:

import Header from "./Header";

Using the Header Component in JSX within App.jsx

Now, use the Header.jsx component inside the App.jsx component:

return (
    <>
        <Header />
        <p>This is my first React App.</p>
    </>
);
Info

By breaking down your UI into smaller components, you can manage and reuse code more effectively, leading to a more organized and scalable application.

Task

Objective: Create a new functional component called Footer.jsx that renders a footer message. Import and use this Footer component in App.jsx below the paragraph.

  1. Create Footer.jsx:

    import React from "react";
    
    const Footer = () => {
        return (
            <>
                <footer>© 2024 React.js Masters Course Team</footer>
            </>
        );
    };
    
    export default Footer;
    
  2. Import Footer in App.jsx:

    import Footer from "./Footer";
    
  3. Use the Footer component in App.jsx:

    return (
        <>
            <Header />
            <p>This is my first React App.</p>
            <Footer />
        </>
    );
    

This task will help you practice creating, importing, and using components in a React application.