Thursday, June 27, 2024

Types of React components

What is React component?
A React component is a fundamental building block of a React application. It encapsulates a piece of the user interface (UI) that can be reused, composed, and maintained independently. It is a self-contained unit of code that defines a part of the user interface. Components can be simple or complex and are written using JavaScript along with JSX (JavaScript XML), which allows you to write HTML-like syntax within your JavaScript code. Eventually, JSX is translated into JavaScript code by Babel transpiler. 

JSX allows you to write HTML-like XML code within JavaScript. JSX is XML based code because it expects XML like well defined tags. You will learn about JSX in separate post. React component can be written without using JSX but as JSX simplifies development of React application, it must be used.

React components can be thought of as custom, reusable HTML elements, which can accept inputs (called "props") and maintain internal state.

Types of React Components

There are mainly two types of React components which are as follows:

  1. Class component
  2. Functional component

Class Components
Definition: These are ES6 classes that extend React.Component and must define a render method that returns React elements.

Example1:

import React from 'react'
export default class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <h3>I am a class Component</h3>
      </div>
    )
  }
}

In above example, MyComponent refers to a class component which inherits render method from its parent component called React.Component

State and Lifecycle: Class components can have their own state and lifecycle methods (like componentDidMount, componentDidUpdate, and componentWillUnmount).

Example2:

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

In the above example, this.props refers to the properties of parent component object and this.props.name refers to name property which is received by Greeting class component. 

React class component can have state which can be updated. Initial state is given in constructor of the class component. In the following example, local state is given in the constructor. The state can be updated using setState function in class component. Note that state is an object.

Example3:

import React from 'react'
class MyComponent extends React.Component {
constructor(props) {
   super(props)

 this.state = {
 firstname:"Bob",
 lastname:"Peterson"
   }
}
   render() {
      return (
  <div>
     <h3>I am a class Component</h3>
     <h4>{this.state.firstname}</h4>
     <h4>{this.state.lastname}</h4>
  </div>
      )
   }
}
export default MyComponent
Lifecycle Methods:
These are special methods in class components that get called at different stages of a component's life, such as mounting, updating, and unmounting. 
Examples are: componentDidMount, shouldComponentUpdate, componentDidUpdate, componentWillUnmount. 

Functional Components:
These are JavaScript functions that accept props as an argument and return React elements. 
Example:
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}
Hooks: Functional components can use React hooks (like useState and useEffect) to manage state and side effects.

Now we look at props and state which are common in both class component and functional component.

Props:
Props (short for properties) are inputs to a component. They are passed to the component as attributes and can be accessed within a component.
Props are read-only and are used to pass data from parent components to child components.
Example: In the following functional component, props is passed as argument. The component receives the data of props from its parent component.

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

In parent component, props data is passed as value of attribute as given below.

ReactDOM.render(<Welcome name="Sara" />, document.getElementById('root'));

State:
Definition: State is a built-in object that stores property values that belong to the component. When the state object changes, the component re-renders.
Usage: State is managed within the component and can change over time, usually in response to user actions. In class component state is managed using this.state and setState method. In functional component, it is managed using hooks. We will see them separately.
Example:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date(),
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Conclusion:
React components are versatile, reusable building blocks that allow developers to create complex and interactive UIs. They manage their own state, can receive data through props, and can be composed together to form more complex UIs. Understanding components is essential for developing applications in React.

A component must be capitalized in React. Why?

In React, component names must be capitalized because React treats components with lowercase names as native HTML elements. This convention helps React distinguish between custom components, which are defined by the user, and built-in HTML elements like `<div>`, `<span>`, `<input>`, etc. Note that HTML elements are in lowercase. Consider the following example:

// Incorrect: Component name is lowercase

const myComponent = () => {

  return <div>Hello, World!</div>;

};

// Correct: Component name is capitalized

const MyComponent = () => {

  return <div>Hello, World!</div>;

};

In the first example, `myComponent` is treated as a native HTML element by React because its name is lowercase. When React sees a lowercase name, it assumes it's a built-in HTML element. As a result, `myComponent` will be rendered as `<myComponent>` in the resulting HTML, which is not what you intend. In the second example, `MyComponent` is capitalized, adhering to the convention. React recognizes `MyComponent` as a custom component and renders it properly as a React component.

By capitalizing component names, you explicitly signal to React that you are referring to a custom component, ensuring proper rendering and avoiding any confusion or conflicts with HTML elements. This convention also enhances code readability and maintainability, making it clear which elements are built-in HTML elements and which are custom React components.

No comments:

Post a Comment

Hot Topics