A picture of a book, a React logo, and a CopyCat logo.

A-Z Guide: All You Need to Know About Reactjs Components

February 17, 2022
copycat
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Introduction

One of the most widely used and robust single-page application libraries in the market today is React.js. It helps create interactive UI elements and render them efficiently with faster page loading time. React components help developers break the UI pages into parts and define singularity with the separation of concerns. These components are the building blocks for any application development. With each react component defined, you can categorise them in terms of why they are needed and their role in the final rendering process. You can follow any aspect of the design pattern by defining shared components, reusable components, higher-order components and many other forms.

Below is an example of a simple shopping application. The React components are divided into different categories to define their purpose and use.

Once you develop a similar design pattern for the React components categorisation, the next thing you need to focus on is how you can use these components to make a robust application. There are different aspects of React components that one should know to use them better. 

  • What are the different ways you can develop a React.js components? 
  • What is the so-called “React.js components Wrapper Hell”, and how to avoid that?
  • How do React.js components interact with each other / How to pass a variable between React.js components?
  • What is the best way to develop a single purpose-driven React component and how do you nest a React component?

Let’s dive deep into each of them to help you get better insights into these questions.

What are the different ways you can develop a Reactjs components? 

There are two ways by which you can develop React components, class components and functional components. Each has its way of handling props, states, and rendering the JSX. You can even use both of them in a single project without running into any issues. Let’s see some code snippets to understand each one of them in detail.

import React from "react";
class ShoppingCart extends React.Component {
  
}

 import React from "react";
export const ShoppingCart = ()=> {
}

As you can see above, class components are simply the class syntactic sugar for the rendering process, while on the other hand, a simple function does the job. You can use even a function expression to create React.js functional components.

Next, Let’s return some JSX from them.

import React from "react";
 
class ShoppingCart extends React.Component {
   render(){
       return(
           <div>
               Shop mart
           </div>
       )
   }
}
import React from "react";
 
export const ShoppingCart = ()=> {
   return(
       <div>
           <div>Shop Mart</div>
       </div>
   )
}

Both have a different way of returning the JSX. React.js Class components need a render function to return the JSX, while React.js functional components return the JSX directly.

Now, when handling props and states, these methods can clash. For a class component to take prop, it has to use ‘this’ representing the current context. The class components lets the React component access the props shared with them and manage the rendering accordingly. And you have to pass props to the superclass inside the constructor compulsorily.

import React from "react";
 
class ShoppingCart extends React.Component {
   constructor(props){
       super(props);
   }
   render(){
       const {martName} = this.props.martName;
       return(
           <div>
               Shop mart welcomes you to {martName}
           </div>
       )
   }
}

But, React.js functional components take the props as a parameter to handle them.

import React from "react";
 
export const ShoppingCart = (props)=> {
   const martName = props.martName;
   return(
       <div>
           <div>Shop Mart welcomes you to {martName}</div>
       </div>
   )
}

The class component has to do a bunch of work in its constructor to manage the state. A class component has to bind the state using ‘this’ and define all the state attributes in an object. And when you have to use the class component, you again need the ‘this’ to target the state.

import React from "react";
 
class ShoppingCart extends React.Component {
   constructor(props){
       super(props);
       this.state = {
           itemsPurchased : 0
       }
   }
   render(){
       const {martName} = this.props.martName;
       return(
           <div>
               Shop mart welcomes you to {martName}
               Total Items Purchased {this.state.itemsPurchased}
           </div>
       )
   }
}

When it comes to React.js functional components, you need hooks to create a state. We will come to hooks in a bit, but before that, let’s see how the useState hook helps you create a state and use them inside the JSX.

import React, { useState } from "react";
 
export const ShoppingCart = (props)=> {
   const [itemsPurchased] = useState(0);
   const martName = props.martName;
   return(
       <div>
           <div>
               Shop Mart welcomes you to {martName}
               Total Items Purchased {itemsPurchased}
           </div>
       </div>
   )
}

React.js Class components to render JSX uses discrete ways of defining each of them in the form of methods. From the phase of mounting to the update phase and till the un-mounting, class components has to define each of them, and then you get control over the JSX if you want any changes while rendering. On the other hand, React.js Version 16, hooks were introduced that let you handle the life cycle but straightforward and less complicated. React hooks are beyond the scope of this article. I would highly recommend you to read about them and get an understanding of how they work.

We have discussed the fundamental differences to clarify the class components and functional components. It is up to the project architect to decide which one to use. 

Apart from the differences that we saw above, React.js functional components require tackling problems like Wrapper Hell to become the fully-fledged purpose serving component. Let’s dive deep into this context in our next section.

What is the so-called “React.js components Wrapper Hell” and how to avoid that?

Before hooks were released, there was no way to reuse the React component logic. Although HOC and Render Props were doing the job, they were not enough. They sometimes created nested wrappers while restructuring the components, and thus Wrapper Hell Issue came. As discussed before, hooks were later introduced, which helped make reusable components and added features to use life cycle methods.

Once your React component is ready, you need to interact between them. We are going to discuss that in the next section.

How do Reactjs components interact with each other / How to pass a variable between Reactjs components ?

To share the data between React.js multiple components, you must first understand their relationship. If you have a Parent-Child relationship, you can share the data using props, and they are passed as params to the components and can be shared. 

Let’s create a Parent component with a simple const value shared with its nested child component Child to understand this better. Also, the Parent component needs some data back from the child based on some specific use case.

Parent Component : 

import React from 'react';
import Child from './Child';
import './style.css';
 
export default function Parent() {
 const childVal = 10;
 const childMethod = (val) => {
   console.log('Child sent ' + val);
 };
 return (
   <div>
     <Child parentMethod={childMethod} parentVal={childVal}></Child>
   </div>
 );
}

Child Component :

import React from 'react';
import Child from './Child';
import './style.css';
 
export default function Parent() {
 const childVal = 10;
 const childMethod = (val) => {
   console.log('Child sent ' + val);
 };
 return (
   <div>
     <Child parentMethod={childMethod} parentVal={childVal}></Child>
   </div>
 );
}

As you see in the above code snippet, the Parent is sending prop to the child component and later, the child is calling the Parent’s passed method to send some data back. Remember, without using a given reference handler from Parent, you cannot send data back from Child to Parent.

One more important thing to note here is that when sending props between React.js multiple components, the left-side value is the reference of the right-side value. The left value always refers to the current component, and the right goes as a prop data that the child can access.

parentMethod={childMethod} parentVal={childVal}

But, If you have a sibling far from the current React component in the tree, then props can be an expensive choice, and you might not want to get into the trouble of prop drilling. Using a global state manager is the best way you can achieve this. You can use the Redux or context APIs to “lift the state up” and broadcast the data globally. 

Using React.js components, you can achieve purpose-driven components, some components broken from their parent components performing a single task. Functional components are the best way to accomplish this, and let’s see how you can get that done.

What is the best way to develop a single purpose-driven React component and how do you nest the ReactJS components?

Breaking your complex React component into a few small child components is the best way to achieve readability and a single purpose-driven component design pattern. Let’s see a code snippet to render the items list on the UI. You could do the rendering process inside the main parent ShoppingCart component. But that is not a good way of writing React.js components. So, you can create a new child component that will take the items list as a prop and do the render job for you and make it single purpose-driven and defines the nesting of the React.js components. In the example below, Child Component is rendered conditionally if the length of the list is more than one. This is done using React JS Conditional Rendering.

import React, { useState } from "react";
 
const RenderItems = ({lisOfItems})=>{
   return(
       {
           lisOfItems.map((items,index)=>(
               <div key={items.id}>{items.label}</div>
           ))
       }
   )
}
 
export const ShoppingCart = (props)=> {
   const lisOfItems = [...]; //some list of items
   const [itemsPurchased,setItemsPurchased] = useState(0);
   const martName = props.martName;
   return(
       <div>
           <div>
               Shop Mart welcomes you to {martName}
               Total Items Purchased {itemsPurchased}
               <RenderItems lisOfItems={lisOfItems}></RenderItems>
           </div>
       </div>
   )
}

Conclusion

Components are the building blocks of React, and with the current trend, Functional programming is becoming more popular in terms of efficient development and reusability. In the end, it all depends on your requirement and use cases, but I hope this article has given a good understanding of the core concepts for components in React and how can you make the best use of them to create interactive react application or web applications.

To better understand conditional rendering in React.js, read this article and for expert React.js practices, visit this article. To turn Figma design to React easier, check out CopyCat, a Figma to React plugin tool for Figma that auto-converts your designs to code. Eliminate sprint delays and speed up development!

Interesting Reads from Our Blogs:

Related Articles

  • React.js

    Master React PropTypes With This Comprehensive Guide

    Introduction In React, we build applications by breaking down the UI into several components. Often, we use React props to pass data from one React component to another. React props allows us to pass different type of data between two…

    July 15, 2022
  • React Best Practices

    A Beginner’s Guide to Maintaining React Applications

    As a beginner React developer, the task of maintaining React applications can be daunting. With so many best practices, tools, and technologies to keep track of, it can be difficult to know where to start. But let me tell you,…

    January 17, 2023

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code