React Components

Piriyalini Niththiyanantham
2 min readMar 8, 2023

--

React Components (Photo from https://www.datarmatics.com/reactjs/03_reacts-learn-about-components/)

Components are the building blocks of the React application. They represent a part of the User Interface. Components are reusable codes and the same component can be used with different properties to display different information. The component can be nested inside other components. In React, Component codes are usually placed in .js files.

There are two ways of writing code for components in React.

  1. Functional component
  2. Class component

Will see the difference between the two types in the next section

Component types

Functional components:

Functional components

These are JavaScript functions. They can optionally receive an object of Properties which is referred to as props and return HTML (JSX) which describes the UI. The way functional component codes represents is shown below.

import React from "react";

const Greet = () => <h1>Hello Priya!</h1>
export default Greet;

Class Components:

Class components

These are regular ES6 classes that extend the Component class from React library. They must contain the render() method, returning HTML. It can input props and output HTML (JSX). Apart from props, a Class component can maintain an internal State. States are private properties for the Class components.

The sample for the Class component is shown below.

import React, {Component} from "react";

class Welcome extends Component{
render(){
return <h1>Class Componrnt</h1>;
}
}
export default Welcome

App.js file with importing Functional and Class Components is given below

import './App.css';
import Greet from './components/Greet';
import Welcome from './components/Welcome';

function App() {
return (
<div className="App">
<Greet/>
<Welcome/>
</div>
);
}

export default App;

Functional vs Class Components: Comparison

Functional vs Class Components

Conclusion

In this Article, we talked about What are components in React, different ways of creating components, why they differ from one another and In which situation we need to use which type of components. Hope this article will be useful. Thank you for reading, Will come up with another concept in React in the next article.

--

--

Piriyalini Niththiyanantham
Piriyalini Niththiyanantham

Written by Piriyalini Niththiyanantham

Undergraduate, Faculty of Information Technology, University of Moratuwa

No responses yet