DEV Community

Cover image for Components in React
Rakshambika
Rakshambika

Posted on

Components in React

What is a Component?

  • A component is simply a JavaScript function that returns JSX.

Example:

function Welcome() {
  return <h1>Hello World</h1>;
}
Enter fullscreen mode Exit fullscreen mode

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>;
}
Enter fullscreen mode Exit fullscreen mode

2. Class Components

Older React applications used class components.

class Greeting extends React.Component {
  render() {
    return <h1>Hello Raksha</h1>;
  }
}
Enter fullscreen mode Exit fullscreen mode

Reusability of Components

A component can be used multiple times.

function Welcome() {
  return <h1>Welcome!</h1>;
}

function App() {
  return (
    <>
      <Welcome />
      <Welcome />
      <Welcome />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome!
Welcome!
Welcome!
Enter fullscreen mode Exit fullscreen mode

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 />
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

This makes the project cleaner and easier to maintain.


Top comments (0)