P4.2: Functional Components
Components are the building blocks of any React application. In this lesson, we will focus on Functional Components, which are standard JavaScript functions that return JSX markup.
Components are the building blocks of any React application. In this lesson, we will focus on Functional Components, which are standard JavaScript functions that return JSX markup.
Lesson: p4-2-components
Components are the building blocks of any React application. In this lesson, we will focus on Functional Components, which are standard JavaScript functions that return JSX markup.
A React component is a self-contained, reusable piece of user interface. Instead of building a website as one giant page, you break it down into modular pieces:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ App Component โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Header Component โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ
โ โ Sidebar Comp โ โ Main Content โ โ
โ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Declaring a component is as simple as writing a JavaScript function. The function's name must start with a capital letter (e.g. Header, not header). This tells React to distinguish it from standard HTML5 tags.
// 1. Declare the functional component
function WelcomeBanner() {
return (
<div className="banner bg-blue-500/10 p-4 rounded-xl border border-blue-500/20">
<h2 className="text-sm font-black text-blue-400">Welcome to React!</h2>
<p className="text-xs text-slate-400">Your coding journey starts here.</p>
</div>
);
}
// 2. Export it for use in other files
export default WelcomeBanner;
You can combine components inside other components (composition). This allows you to construct complex layouts out of simple, testable pieces.
import WelcomeBanner from "./WelcomeBanner";
function Dashboard() {
return (
<div className="p-6 space-y-4">
<h1 className="text-xl font-bold">Admin Panel</h1>
{/* Rendering our component nested inside Dashboard */}
<WelcomeBanner />
<p className="text-xs text-slate-500">All systems operational.</p>
</div>
);
}
[!CAUTION] Never Nest Component Definitions! You should always declare components at the top level of your files. Nesting a component definition inside another component function will cause React to rebuild the inner component type on every render, causing severe performance issues and bugs.
Historically, React used Class Components, but modern React applications use Functional Components exclusively.
Percentage of modern web dev teams using Functional Components with Hooks.