Your First React Component
Components are the fundamental building blocks of any React application. Think of them as custom, reusable HTML tags that encapsulate structure, styling, and behavior.
What is a Functional Component?
In modern React, a component is simply a JavaScript function that returns React elements (usually written in JSX).
function WelcomeMessage() {
return <h1>Hello, Welcome to React!</h1>;
}
The Rules of Components
- PascalCase Naming: Component names must start with a capital letter (e.g.,
Button,UserProfile,Navigation). If you name a component starting with a lowercase letter (e.g.,button,header), React will treat it as a standard HTML DOM tag and your component will fail to render correctly. - Return Single Root Element: A component must return a single parent element. If you need to return multiple siblings, you must wrap them in a parent
<div>or a Fragment (<> ... </>).
// Valid
function ValidComponent() {
return (
<>
<h1>Title</h1>
<p>Paragraph</p>
</>
);
}
Exporting Components
For a component to be used in other parts of your application, it needs to be exported from its file. There are two main ways to export components:
Default Export (Standard Practice for Components)
A file can only have one default export. This is usually the main component of that file.
// Greeting.jsx
import React from 'react';
function Greeting() {
return <h2>Hello there!</h2>;
}
export default Greeting;
When importing a default export, you can name it whatever you want (though keeping the original name is best practice):
import Greeting from './Greeting';
Named Exports
You can have multiple named exports in a single file. This is useful for utility functions or exporting multiple smaller components from one file.
// Buttons.jsx
export function PrimaryButton() { /* ... */ }
export function SecondaryButton() { /* ... */ }
When importing named exports, you must use curly braces and the exact name:
import { PrimaryButton, SecondaryButton } from './Buttons';
Rendering a Component
Once a component is defined and exported, you can use it inside other components just like an HTML tag.
// App.jsx
import React from 'react';
import Greeting from './Greeting'; // Importing our component
function App() {
return (
<div className="app-container">
<h1>My First App</h1>
{/* Rendering the component */}
<Greeting />
<Greeting />
</div>
);
}
export default App;
In the example above, the App component renders the Greeting component twice. This demonstrates the core power of React: creating reusable, independent UI elements.