Components in React

React, a JavaScript library for building user interfaces, relies heavily on the concepts of components and props to create modular and reusable code. Let’s explore these fundamental concepts.

Components:

What is a Component?

In React, a component is a self-contained, reusable building block that encapsulates a piece of the user interface and its behavior. Components allow developers to break down complex UIs into smaller, manageable parts, making code organization and maintenance more straightforward.

Types of Components:

1.Functional Components:

  • Also known as stateless components.
  • Written as JavaScript functions.
  • Mainly responsible for rendering UI based on the input props.
const FunctionalComponent = (props) => {
  return <p>{props.message}</p>;
};

2. Class Components:

  • Also known as stateful components.
  • Written as ES6 classes.
  • Can hold and manage local state in addition to rendering UI.
class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return <p>Count: {this.state.count}</p>;
  }

Creating Components:

Functional Components:

const MyFunctionalComponent = () => {
  return <p>Hello, I'm a functional component!</p>;
};

Class Components:

class MyClassComponent extends React.Component {
  render() {
    return <p>Hello, I'm a class component!</p>;
  }
}

Related Post