React 101 – Part 2: Introduction to React Components -A Comprehensive Guide to Building Modern User Interfaces

Components in ReactJS

A component is one of the main building blocks of React. With other terms, we may say that every application you design with React will be built up of bits called components. Components make the work of building UIs considerably easier. You can view a UI broken down into numerous discrete elements called components, work on them independently, and integrate them all into a parent component, which will be your final UI.

Components in React simply return an element of JSX code that indicates what should be presented on the screen.

Types of components in ReactJS

In React, we generally have two sorts of components:

Functional Components: Functional components are essentially javaScript functions. We can create a functional component in React by writing a javaScript function. These functions may or may not receive data as parameters, we will address this later in the tutorial. The next example displays a valid functional component in React:

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

Class Components: The class components are a little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to another class component. We can use JavaScript ES6 classes to create class-based components in React. The below example shows a valid class-based component in React: 

class testcomponent extends React.Component {
    render() {
        return <h1>Welcome to React!</h1>;
    }
}

Here, We have established the major distinction between a functional component and a class component by generating components in the previous two cases. Other properties of class-based components will be covered in forthcoming courses.

Where we use functional component ?

We are going to use functional components only when we know for sure that the component does not need to interact with or work with any other components. It is because functional component don’t require data from other components. however we can compose many functional components beneath a single functional component.

How to Render Components in ReactJS

React also has the ability to render user-defined components. In React, we can either create an element with a user-defined component and send this element as the first parameter to ReactDOM.render(), or we may directly pass the component as the initial argument to the ReactDOM.render() method.

Syntax to initialize a component

const newElement = <NewElement />;

here I use const variable as newElement component also named ‘NewElement’. it can be vairy on your project. You can use any name that you wish. here is just an example. Here are some things you need to know

  • Component should begin with a capital letter

here is a example

import React from 'react';
import ReactDOM from 'react-dom';

//Functional component
const Hello = () => {
     return <h1> Hello World </h1>
}

ReactDOM.render(
     <Hello />,
      document.getElementById("root")
);

Summary of above code

This code is a small React application that displays a “Hello World” message on a web page. Here’s a quick rundown of what it does:

  • Import React and ReactDOM: The code begins by importing the libraries React and ReactDOM, which are required for constructing and rendering React apps.
  • Define a Functional Component: It defines a Hello functional component. This component is a JavaScript function that returns JSX (a JavaScript syntax extension used in React). In this instance, it returns a h1> element with the phrase “Hello World.”
  • ReactDOM.render(): The Hello component is rendered to the DOM  using this method. It requires two arguments:
  • The first argument, Hello />, is the React component to be rendered. It’s the Hello functional component in this situation.
  • The second option is document.getElementById(“root”), which specifies the DOM element to which the component should be displayed. It searches the document for an HTML element with the ID “root”.
  • Rendering: When ReactDOM.render() is invoked, the output of the Hello component replaces the content of the HTML element with the ID “root” (usually a div> element). As a result, the text “Hello World” will be shown within a h1> element on the web page.

Overall, this code creates a basic React application that renders the Hello functional component within a specified DOM element to show “Hello World” on a web page.

ReactJs functional components and class components

Functional Components

Earlier we discussed about there are two types of components in React. So now we are going talk about Functional Component into more depth.

  • Functional components are more common when we are working with ReactJS.
  • Simply these components are JavaScript functions.
  • In React, Functional component can be written using JavaScript function.
  • The function mentioned above can or cannot accept data as parameters. However, this can vary depending on the scenario.
  • The return value in functional Components is the JSX code to render to the DOM tree.

Here you can see example of the functional component. Now Don’t think about useState(). You will be learning it in the upcoming tutorial about Hooks.

import React, { useState } from 'react';

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

  // Event handler to increment the count
  const handleIncrement = () => {
    setCount(count + 1);
  };

  // Event handler to decrement the count
  const handleDecrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h1>Counter</h1>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
      <button onClick={handleDecrement}>Decrement</button>
    </div>
  );
}

export default Counter;

Advantages of Functional components

  • Simplicity & Readability– functional components more easier to read when compared with class components. They utilize a simple JavaScript function, which simplifies the component’s structure.
  • Performance – Have faster execution than class components.
  • Reusability – Functional components can be separated faster into custom hooks, making it easier to reuse state logic across multiple portions of your application.
  • Hooks – React Hooks such as useState, useEffect, and useContext are seamlessly supported by functional components, making it easier to manage state, side effects, and context within the component.

Disadvantages or Problems of using functional components

  • No Lifecycle methods – Functional component don’t have componentDidMound and ComponentDidUpdate like lifecycle methods.
  • Debugging complexity – when it comes to debugging process functional components can be slightly challenging than class components in scenarios like working with complex state changes.
  • Backward Complexity – If you already have a codebase using class components, switching to functional components may necessitate extensive refactoring.
  • When compared with class-based components (Class Components) some features are lack in functional components.

Class Components

Class components are used to develop modern web apps build in ReactJS. These are simple classes which are made using multiple functions that can add various functionality to the app. All class components are child classes of ReactJS’s Component class.

Example for class component. This is the same example use to functional component. but here it is refactored to the class component.

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  handleIncrement = () => {
    this.setState({ count: this.state.count + 1 });
  };

  handleDecrement = () => {
    this.setState({ count: this.state.count - 1 });
  };

  render() {
    return (
      <div>
        <h1>Counter</h1>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleIncrement}>Increment</button>
        <button onClick={this.handleDecrement}>Decrement</button>
      </div>
    );
  }
}

export default Counter;

Advantages of Class Components

  • Lifecycle method – Above we mentioned in functional component don’t have componentDidMount, componentDidUpdate and componentWillUnmount lifecycle. But in here Class components we have all of them.
  • Instance Properties – You will be able to define instance properties using this. example (this.state, this.props) It is can be easily accessible within the component.
  • Controlled components – Class components are widely used to create controlled form elements, in which the component maintains the state and behavior of the form.
  • Existing codebase – If you already have a codebase with class components, it may be easier to keep them instead of converting them to functional components, and this process will be more time consuming.
  • Separation of Concerns – Class components naturally encourage isolating rendering functionality (render method) from other concerns, such as event handling and side effects.

Disadvantages of Class Components

  • Complexity – When compared to functional components, class components can be more sophisticated and verbose. They necessitate the creation of constructors, the manual binding of event handlers, and the use of this keyword, which can result in boilerplate code.
  • Readability – The structure of class components might make the code more difficult to read and understand, especially for React beginners.
  • Performance – When compared with functional components, class component have less performance.
  • No Hook Support – React Hooks, which can help with state management and side effects, are not supported by class components. Hooks are only available as functional components.

Yeah.. So far, so good, right?

Ok. Then we will meet with React Hooks on an upcoming article. Until then, Stay safe

You can find React 101 Tutorial Part 1 from here

You can find more additional info by following React Official Documentation

Leave a Comment