Component And Its Types In ReactJS

In this article, we will discuss what is a component, details about components, and finally the types of components.
 

Components

 
A component is a piece or part of the user interface. The heart of all react applications is a component. Every react application contains at least one component and it can contain multiple components also. ReactJS allows us to create reusable components. There can be one root component (in our case it is the app component) and which can contain nested components like header, body, and footer components.
 

Component Code

 
A component code is usually placed in a javascript file (Or .js file). For example, our App component (which is our root component) is placed inside the App.js file. Our App component (Or root component) looks like this,
 
Component And It's Types In ReactJS
 
We can also use the component file with .jsx extension and which looks like this,
 
Component And It's Types In ReactJS
 

Types of Components

 
There are two types of components present such as,
  • Functional Component
  • Class Component

Functional Component

 
Functional components are about our javascript functions which return html that describes our User Interface (Or UI).
 
Example
  1. function Test(){  
  2.    return <h1>Hello Jim</h1>;  
  3. }   
Functional components are just javascript functions they can optionally receive an object of properties which is referred to as props and return HTML (JSX) which describes the User Interface (Or UI).
 
Example
  1. function Test(props){  
  2.    return <h1>Hello {props.name}</h1>;  
  3. }   
We can also write the functional component using the ES6 arrow function which is as below,
 
Example
  1. const Test = () => <h1>Hello Jim</h1>   
A functional component is simple functions that don’t contain this keyword. It doesn’t contain a state and mainly responsible for the User Interface (Or UI).
 

Class Component

 
Class components on the other hand are regular ES6 classes that extend from component class from react library. They must contain a render method that returns html.
 
Example
  1. class Test extends React.Component{  
  2.    render(){  
  3.       return <h1>Hello, {this.props..name}</h1>;  
  4.    }  
  5. }   
The class component can optionally receive props as input and return html (Or JSX). They are feature-rich and maintain their private data called a state. It can handle complex UI logic and provide lifecycle hooks. 


Next Recommended Reading Bind Data To Table Using ReactJS And MVC