30 April 2026

What is Component in React.js

 What is Component in React.js

In React, a Component is a self-contained, reusable building block of the user interface (UI).

In a website, You can build a "Button" component, a "Navbar" component, and a "ProfileCard" component, then piece them together to create a complex application.


Core Concepts

  • Declarative: You describe what you want the UI to look like based on the current data, and React handles the actual DOM updates.

  • Reusable: You can write a component once and use it multiple times throughout your app with different data.

  • Independent: Components manage their own logic and appearance, making code easier to debug and scale.

The Two Types of Components

Previously, React relied heavily on Class Components, but modern React development almost exclusively uses Functional Components because they are simpler and more concise.

1. Functional Components (Modern Standard)

These are just JavaScript functions that return JSX (code that looks like HTML).

JavaScript
function WelcomeMessage() {
  return <h1>Hello, User!</h1>;
}

2. Class Components (Legacy)

These use ES6 classes. While you might see them in older codebases, they are rarely used in new projects.

JavaScript
class WelcomeMessage extends React.Component {
  render() {
    return <h1>Hello, User!</h1>;
  }
}

How Components Communicate

Components don't just sit there; they interact using two main concepts:

  1. Props (Properties): Think of these as "arguments" passed to a function. They allow a parent component to pass data down to a child component.

  2. State: This is the component's "memory." It allows a component to keep track of information that might change over time (like whether a checkbox is clicked or data from an API).

Example: Putting it all together

Here is a simple example of a Profile component that receives data via props:

JavaScript
// The Component Definition
function Profile(props) {
  return (
    <div className="card">
      <h2>{props.name}</h2>
      <p>Occupation: {props.job}</p>
    </div>
  );
}

// Using the Component
function App() {
  return (
    <div>
      <Profile name="Alice" job="Developer" />
      <Profile name="Bob" job="Designer" />
    </div>
  );
}

Why use Components?

  • Consistency: Change the code in one file (e.g., Button.js), and every button in your app updates instantly.

  • Readability: Instead of looking at 1,000 lines of HTML, you see clear tags like <Navbar/> and <Footer/>.

  • Collaboration: Different developers can work on different components simultaneously without stepping on each other's toes.

No comments:

Post a Comment

Comments Welcome

Finding duplicate records in SQL Server

 Finding duplicate records in SQL Server 1. The GROUP BY and HAVING Method This is the most standard approach. It is best used when you on...