What are React Components? Introduction to Components | Types of Components

Himadrikhali
3 min readMay 1, 2023

--

What is a Component?

A component is an independent, reusable bit of code which divides the UI into smaller pieces. For example, if we were building the UI of React website using Reactjs we can break its UI into smaller parts as shown in the figure.

Instead of building the whole UI under one single file like HTML, we can divide all the sections (marked with red) into smaller independent pieces. In other words, these are components. Each component will go into its own JavaScript file.

In React we have two types of components: functional and class. Let’s look at each type of component in more detail. But before that, let’s gain an understanding of extraction of components.

Extracting Components

As you know, everything in React is a component. Each component returns some HTML but we can return only a single HTML element; inside which we can write many child elements as we have seen in the examples. Instead of writing all the code in a single file we can split our app into multiple components.

We can then extract the code which is used for some unique purpose into a separate component and use that component wherever we want in our app, instead of rewriting and duplicating the code.

In the following examples we have already extracted components into

  1. HelloWorld.js: For rendering the title
  2. Description.js: for rendering the description

Now I can use both the components in any place inside the app without duplicating the code. This is called extracting and reusing components .

What are Functional Components?

The first, most important and recommended component type in React is a functional component. A functional component is basically a JavaScript function that returns a React element (JSX).

Functional components start with function keyword.

Code:

Alternatively, you can also create a functional component with the arrow function syntax(ES6).

Code:

What are Class Components?

Another type of component is a class component. Just as we have functions, we also have classes in JavaScript. Class components are ES6 classes that return JSX. The same HelloWorld function can be converted to a class component.

Class components start with class keyword that extends the Component constructor from React and has a render method which returns a JSX.

Code:

--

--

Himadrikhali

As a technical trainer, I aim to provide timely updates to students on how to use new technology and troubleshoot errors to ensure a seamless experience.