4. Creating and Using Functional Components
What Are Components?
Components are the building blocks of a React application. Think of them like Lego pieces — each piece does a small job, and when you combine them, you build full pages and apps.
In this course, we'll focus on **functional components**, which are the most common way of writing React components today.
Your First Functional Component
A functional component is just a JavaScript function that returns JSX.
function Message() {
return <p>This is my first component!</p>
}
export default Message;Using (Importing) a Component
To use a component, import it and include it inside JSX like a custom HTML tag.
import Message from './Message'
function App() {
return (
<div>
<h1>Welcome to React</h1>
<Message />
</div>
)
}
export default App;Component Naming Rules
- Component names must start with a capital letter.
- Each component must return a single parent element.
- Every component should be reusable and do one job if possible.
Splitting UI Into Components
Instead of writing everything in one big file, break your UI into smaller, reusable components. This makes your code easier to read and manage.
function Header() {
return <header><h2>My Website</h2></header>
}
function Footer() {
return <footer><p>Copyright 2025</p></footer>
}
function App() {
return (
<div>
<Header />
<p>Welcome to my page!</p>
<Footer />
</div>
)
}Mini Project Step
Inside your `src` folder, create a new folder called `components`. Add three files: `Header.jsx`, `Hero.jsx`, and `Footer.jsx`. Build basic functional components inside them and import them into `App.jsx`.
// Header.jsx
function Header() {
return <h1>React Course Project</h1>
}
export default Header;
// Hero.jsx
function Hero() {
return <p>Learning React one step at a time.</p>
}
export default Hero;
// Footer.jsx
function Footer() {
return <small>Built with ❤️ in React</small>
}
export default Footer;
// App.jsx
import Header from './components/Header'
import Hero from './components/Hero'
import Footer from './components/Footer'
function App() {
return (
<div>
<Header />
<Hero />
<Footer />
</div>
)
}
export default App;