Components
Components are the heart and soul of React. Think of them as custom HTML elements that you create. A component is just a JavaScript function that returns JSX. That's it! No magic, no complex classes - just functions that describe what should appear on screen.
Remember the LEGO analogy from the introduction? Each component is a LEGO brick. It's independent, reusable, and does one thing well. You compose components together to build your entire application, just like snapping LEGO pieces together.
Function Components
Function components are the modern way to write React components. They're simple, clean, and easy to understand. Just write a function that returns JSX, and you've got yourself a component. The function name becomes the component name.
function Greeting() {
return <h1>Hello, World!</h1>;
}
function UserCard() {
return (
<div className="card">
<h2>John Doe</h2>
<p>Web Developer</p>
</div>
);
}
See how clean that is? Each component has a single responsibility. Greeting displays a greeting message. UserCard displays a user's information. Simple, focused, and easy to maintain.
Composing Components
Here's where the magic happens. Components can include other components, creating a tree structure. This is how you build complex UIs - by breaking them into smaller, manageable pieces. It's like having a conversation where each person speaks their part.
function App() {
return (
<div className="app">
<Header />
<MainContent />
<Footer />
</div>
);
}
function Header() {
return <nav>My App</nav>;
}
function MainContent() {
return <main>Welcome to my app!</main>;
}
function Footer() {
return <footer>ยฉ 2026</footer>;
}
Notice how App is composed of Header, MainContent, and Footer. Each component handles its own piece of the UI. This makes your code organized and your components reusable. Need that Header on another page? Just import and use it!
Exporting and Importing
To use a component in another file, you need to export it from where it's defined and import it where you want to use it. Use export default for the main component in a file, and export (without default) for multiple exports.
export default function Button() {
return <button>Click Me</button>;
}
import Button from './Button';
function Form() {
return (
<form>
<input type="text" />
<Button />
</form>
);
}
The import path is relative to the current file. './Button' means look in the same folder. '../Button' means go up one folder. This module system keeps your code organized and prevents naming conflicts.
Try it Yourself โ