Basic Of Functional Components And Class Components

Introduction 

In my previous article, we covered the basics of the React js app and its folder structures. Now, we will cover components in React and how to use them. So, let’s start.

Component

Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. By using components UI building will be very easier.

In simple words, for a single page website we can have 3 different components like header, main content & footer component. And we can split these components into multiple components as well.

In React we have mainly two types of components.

  • Functional Component (Stateless component)
  • Class Component (Stateful component)

Functional Component

Functional components are simply JS functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters.

function FunctionComp() {
    return( <h3> Hello! from Function component</h3>)
}
export default FunctionComp;

Demo

Open react js application in VS code and run it using “npm start” in terminal window.

Create a new js file named as “FunctionComp.js” (go to Src folder a click on Add new File).

Create simple function component as below and export it so that we can use it anywhere using import.

Now go to app.js and import this component and use it.

Save it and go to browser, we can see message from function component which we have created.

Basic Of Functional Components and Class Components

Class Component

The class components are a little more complex than the functional components and it’s an ES6 class that extends the Component class from React library. Class component must have render method.

Code

import React,{Component } from 'react'
class ClassComp extends Component{
    render(){
        return <h3>Hello! from Class component</h3>
    }
}
export default ClassComp;

Demo

Go to Src folder and create a new js file and name it as “ClassComp.js” and add code as below.

To use class Component,

  • Import component from react library
  • Extend the class by using “extend” keyword with Component.
  • Render method should be there in class component.

Go to App.js file and import this class component and use it.

Summary

In this article, we have covered components in React, how many types of components there are and how we can use them in our react js applications. Components are building a block of React js and can be reused and nested within other components. They play a very important role in React applications.