What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most frontend development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Componentbased Architecture in web development.  

I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  

But first, what is Componentbased Architecture? 

In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. 

So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? 

The word “component” in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.

There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: 

React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? 

A very simple components looks something like this:

Alright. But<Greeting /> is not recognised by web browsers so won’t it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  

JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. Igives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. 

But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. 

React.create Element is part of React API which actually defines a React elementThis data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  

Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. 

There are two types of components based on interactivity: 

Stateless Component: When a React componentdoesn’t have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn’t provide any user interactivity with component. For Ex: above Greeting component <Greeting name=”John Smith” /> is a stateless component as it just renders the information (in this case name props) passed to it. 

Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:

Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

Based on Programming Methodology 

There are two type of components based on Programming Methodology 

Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:

Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. 

There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. 

Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. 

Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.

In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  

React lifecycle

React lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ 

To understand component’s lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting 

Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument – props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:

constructor 

getDerivedState From Props 

render 

componentDidMount 

getDerivedState From Props 

should Component Update 

render 

getSnapshot Before Update 

component Did Update 

Unmounting: Last phase of React component is unmount. it invokes the last method of React component’s lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:

As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. 

First check the NodeJS and NPM installation on machine by executing following command: 

In case NodeJS is not install then download and install it from https://nodejs.org/en/. 

Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: 

npx create-react-app My First React Project 

NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: 

cd My First React Project 

npm start 

This would start a local server at port number 3000 and open default React page in browser.

React page in browser

Above image shows the files and folder generated by CRA. let us go through it and understand: 

CRA configured our React project with all the needed tooling required for web development. It configured Webpackdev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslintreact-testing-library for unit testing React components etc… 

src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. 

So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.

Let’s create our first stateful functional component. We will be building a simple counter component. The final output looks like this: 

Counter component code: 

export default Counter; 

Styles are added in Counter.css 

We have created a fully functional counter component which can be used anywhere in React application.

  • Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. 
  • Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. 
  • Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. 
  • Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.
  • Stateless Component: When a React componentdoesn’t have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn’t provide any user interactivity with component. For Ex: above Greeting component <Greeting name=”John Smith” /> is a stateless component as it just renders the information (in this case name props) passed to it. 

  • Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:

  • Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:

  • Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. 

  • Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. 

  • Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.

  • Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument – props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:

  • constructor 

  • getDerivedState From Props 

  • render 

  • componentDidMount 

  • Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:
  • getDerivedState From Props 

  • should Component Update 

  • render 

  • getSnapshot Before Update 

  • component Did Update 

  • Unmounting: Last phase of React component is unmount. it invokes the last method of React component’s lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:

  • package.json: This file contains NPM dependencies, NPM scripts, project name, version etc… 
  • public folder: All public assets will be present in public folder like index.html, image or logo etc… 
  • src folder: All our JS code including React components will be present in src folder. 
  • Research & References of What Is a React Component? Write Your First React Component|A&C Accounting And Tax Services
    Source