React Fundamentals

Learn React from scratch including components, JSX, props, and state basics.

beginner Frontend Frameworks 5 hours

Chapter 4: Components Basics

Chapter 4 of 15

Chapter 4: Components Basics

4.1 Function Components

Components are the building blocks of React applications. Function components are the modern way to create components.

// Function component
function Welcome() {
    return <h1>Hello, World!</h1>;
}

// Arrow function component
const Welcome = () => {
    return <h1>Hello, World!</h1>;
};

// With implicit return
const Welcome = () => <h1>Hello, World!</h1>;

Component Characteristics:

  • Must return JSX (or null)
  • Name starts with capital letter
  • Can contain other components
  • Reusable and composable

Component Structure:

function UserCard() {
    return (
        <div className="user-card">
            <h2>User Name</h2>
            <p>User email</p>
            <button>View Profile</button>
        </div>
    );
}

4.2 Component Usage

Use components like HTML elements in JSX.

// Using component
function App() {
    return (
        <div>
            <Welcome />
            <Welcome />
            <Welcome />
        </div>
    );
}

// Components can be nested
function App() {
    return (
        <div>
            <Header />
            <Main>
                <Sidebar />
                <Content />
            </Main>
            <Footer />
        </div>
    );
}

Component Composition:

  • Build complex UIs from simple components
  • Each component has single responsibility
  • Components can contain other components
  • Promotes reusability

4.3 Component Organization

Organize components for maintainability.

File Structure:

components/
├── Header/
│   ├── Header.js
│   ├── Header.css
│   └── Header.test.js
├── Button/
│   ├── Button.js
│   └── Button.css
└── Card/
    ├── Card.js
    └── Card.css

Component Types:

  • Presentational: Focus on UI, receive data via props
  • Container: Handle logic and state
  • Layout: Structure and positioning
  • Feature: Complete feature implementation

4.4 Component Best Practices

Follow best practices for component development.

  • Keep components small and focused
  • Use descriptive component names
  • Extract reusable logic
  • Separate concerns (presentation vs logic)
  • Use composition over inheritance