Ads Top

React Basics: Types Of Components

What is a Component in React?

From the Facebook documentation: Components let you split the UI into independent, reusable pieces, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.

As plainly stated above, one of the main advantages of components is taking potentially large pieces of code that make up views and break them down in the smaller more manageable pieces that are easier to work with.

As mentioned in my post React Basics: Beginning To Learn React, there are 3 main types of components. They are:
  • Functional
  • Class
  • Container

Functional Component

Some info comes in (props), and some JSX comes out (being displayed). Notice how the syntax looks. It is a standard Javascript function.

Class Component

A component that needs to be aware of its own state In React, when we refer to state, we are saying a plain javascript object used to record and react to user events.

Each class based component we define has it’s own state based object. Whenever a component state is changed, the component immediately rerenders. It will also rerender its child components Before you use state inside a component, you need to initialize the state object.

To set the property state, to a plain js object inside of the class constructor method.

While trivial, the following example makes it easy to follow the basics of a class component.

A few key points
1: class Welcome extends Component: This is how you define an ES6 class based component. When declaring, you need to have the following import at the top of your file.

import React, { Component } from 'react';
Destructuring { Component } from react allows you to define the class like this
class Welcome extends Component
Instead of like this
class Welcome extends React.Component
2: A class component always needs a render() method and always needs to return() something.


Containers

A container is a class based component that has all the ability of a regular class based component plus it can connect to the redux store via the connect() method.

2 comments:

  1. Interesting blog post on ReactJS Components. Thanks for writing this good content.

    Best Regards,
    ReactJS Institute in Ameerpet, Hyderabad

    ReplyDelete
  2. Hey James,
    Thanks for writing such a Great Tutorial!
    -Dipti

    ReplyDelete

Powered by Blogger.