What is a Component?
- A component is simply a JavaScript function that returns JSX.
Example:
function Welcome() {
return <h1>Hello World</h1>;
}
Here:
- Welcome is a component.
- It returns an
<h1>element. - React renders the returned JSX on the screen.
Why Do We Need Components?
Without components, we would have to write the same code repeatedly. Components help us:
- Reuse code
- Keep code organized
- Improve maintainability
- Build complex UIs easily
Types of Components
1. Functional Components
Modern React mainly uses functional components.
function Greeting() {
return <h1>Hello Raksha</h1>;
}
2. Class Components
Older React applications used class components.
class Greeting extends React.Component {
render() {
return <h1>Hello Raksha</h1>;
}
}
Reusability of Components
A component can be used multiple times.
function Welcome() {
return <h1>Welcome!</h1>;
}
function App() {
return (
<>
<Welcome />
<Welcome />
<Welcome />
</>
);
}
Output:
Welcome!
Welcome!
Welcome!
This demonstrates the reusability of components.
Real-World Example
Imagine building a portfolio website.
Instead of writing everything in one file, create separate components:
- Header Component
- About Component
- Skills Component
- Projects Component
- Contact Component
- Footer Component
Then combine them inside App.jsx.
function App() {
return (
<>
<Header />
<About />
<Skills />
<Projects />
<Contact />
<Footer />
</>
);
}
This makes the project cleaner and easier to maintain.
Top comments (0)