Skillversitas

Components

What is a Component?

A component is a building block of UI in React. Every component is a JavaScript function that returns JSX describing a part of the interface.

Function Components

Function components are the modern, recommended way to write components.

function Header() {
  return (
    <header>
      <h1>My Website</h1>
      <nav>
        <a href="#home">Home</a>
        <a href="#about">About</a>
      </nav>
    </header>
  );
}

Class Components

Class components are the old way. A lot of legacy code still uses them, so it is important to recognize them.

import React, { Component } from 'react';

class Header extends Component {
  render() {
    return (
      <header>
        <h1>My Website</h1>
      </header>
    );
  }
}

The focus of this tutorial is function components, because they are the current standard.

Export and Import

Each component typically lives in its own file. Use export default and import to connect them.

// Header.jsx
function Header() {
  return <h1>My Website</h1>;
}

export default Header;
// App.jsx
import Header from './Header';

function App() {
  return (
    <div>
      <Header />
    </div>
  );
}

export default App;

Nested Components

Components can be nested inside other components to build complex UI structures.

function App() {
  return (
    <div>
      <Header />
      <main>
        <Content />
      </main>
      <Footer />
    </div>
  );
}

function Header() {
  return <header><h1>Title</h1></header>;
}

function Content() {
  return <section><p>Page content</p></section>;
}

function Footer() {
  return <footer><p>&copy; 2024</p></footer>;
}

Children Prop

children is a special prop that contains all the elements between a component's opening and closing tags.

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}

function App() {
  return (
    <Card>
      <h2>Card Title</h2>
      <p>The card content is here.</p>
    </Card>
  );
}

children lets you create flexible wrapper components.

Summary

Components are the foundation of every React application. Start with function components, use export/import for modularity, and leverage nesting and children for an organized UI structure.

In the next chapter, we will learn about Props — how data is sent from a parent component to a child component.