React Components Explained with Examples

Jun 04 20232 min read
React Components Explained with Examples

Components are reusable pieces of code that are independent of each other and can be combined to build the application.

A react application is made up of multiple components which can be parent or child to each other but in the end, they all return HTML elements that are rendered in the browser.

Components can be nested.

A component name should start with a capital letter, although there is no strict naming convention.

There are 2 types of components. We will see an example written in both ways.

Class component

A class component is a class that extents React.Component class. This class contains a method called render() which you must override in your class and return your element. The element can be HTML element or another React component. See the below example.

import React from "react";

export default class Book extends React.Component {

    render() {
        return <h1>This is a book</h1>
    }
}

You need to export the component so that it can be imported into other files and could be used.

Rendering the component

To reflect your component in the UI, you have to render it in the document. See the example below.

import React from 'react';
import ReactDOM from 'react-dom';
import Book from "./book";

ReactDOM.render(<Book/>, document.getElementById('root'));

ReactDOM is a React class that renders the component into the document. The render() method takes the component to be loaded, and place in the document where it needs to be loaded.

It produces the following output.

The same example can be written as a functional component also. Check more details on class components below.

React class component with example

Function component

The function component is like a JavaScript function that returns an HTML element. Functional components are written using less code and are easier to maintain. They are preferred over class components.

import React from "react";

export default function Book() {
    return <h1>This is a book</h1>
}

or

import React from "react";

const Book = () => {
    return <h1>This is a book</h1>
}

export default Book

The function components can be rendered the same way we rendered class component.

Complete example

Write the below code in the index.js file and it will render the Book component in the element with id root.

import React from 'react';
import ReactDOM from 'react-dom';
import Book from "./book";

ReactDOM.render(<Book/>, document.getElementById('root'));

The element that comes from the Book component will be rendered in the root element in the document. The output is same as the class component.

Check more details of functional components below.

React function components with example