About Components in React

What is a Component?

  • A component is a reusable, self-contained piece of UI.

  • Think of components as JavaScript functions or classes that return React elements (JSX) describing what should appear on the screen.

  • Components can be small and simple (like a button) or complex and composed of many smaller components.


Why Use Components?

  • Reusability: Write once, use many times.

  • Maintainability: Break UI into manageable chunks.

  • Encapsulation: Each component manages its own structure, styles, and behavior.

  • Composition: Components can contain other components to build complex interfaces.


Types of Components

Type Description Example
Functional Component A JavaScript function returning JSX function Greeting() { return <h1>Hello!</h1>; }
Class Component ES6 class extending React.Component with a render() method class Greeting extends React.Component { render() { return <h1>Hello!</h1>; } }

Functional Components (Modern Standard)

jsx
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}

Or using arrow functions:

jsx
const Welcome = (props) => <h1>Hello, {props.name}!</h1>;

Class Components (Older Syntax)

jsx
import React, { Component } from 'react';

class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}


Using Components

jsx
function App() {
return (
<div>
<Welcome name="Alice" />
<Welcome name="Bob" />
</div>
);
}

Props: Passing Data to Components

  • Props are inputs to components — like function arguments.

  • They allow components to be dynamic and reusable.

Example:

jsx
<Welcome name="Charlie" />

The component uses the name prop to customize the output.


State: Components’ Internal Data

  • Components can have state, data that can change over time.

  • Functional components use hooks like useState for state management.

  • Class components use this.state.

Example (Functional with state):

jsx
import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}


Summary

  • Components are the core building blocks of React.

  • They are reusable, composable, and encapsulate UI and logic.

  • Modern React prefers functional components with hooks.

  • Use props to pass data in, and state to manage internal dynamic data.

Leave a Reply

Your email address will not be published. Required fields are marked *