web-development top banner

What Is a React Component?

Read it in 12 Mins

Last updated on
20th Apr, 2021
Published
20th Apr, 2021
Views
9,312
What Is a React Component?

React is one of the most popular JavaScript libraries for building user interfaces. If you are thinking of getting into front-end development or web developmentthen learning React will be a good way to start. 

In this blog you are going to learn basic concepts in React such as components and their types, JSX syntax and props. Lets start with JSX. 

What is JSX? 

Soon after installing React project, if you open App.js in your favourite editor you will observe that a JavaScript function returns some HTML code. It is called JSX(JavaScript XML). 

What are the components in React JS

This is a valid and widely accepted syntax extension to JavaScript. It is recommended to use it to describe what the UI should look like 

In frontend-related projects, we keep HTML, CSS, and JavaScript code in separate files. However, React works a bit differently. In React we don’t create HTML files because JSX allows us to write HTML and JavaScript combined in the same file. But CSS needs to be separated to a new file as shown in the figure (App.css). 

Why JSX? 

  • Within JSX we can add JavaScript(logic, functions, variables etc) as well by using curly braces { } inside the HTML as shown in the figure. 

What are the components in React JS

  • We can assign HTML tags to JavaScript variables: 

Code: 

 var name = <p>React</p>;

What are the components in React JS

 Here, we have assigned HTML to name variable. 

  • You can return HTML conditionally (such as if-else cases): 

Code:

functionApp() { 
  var condition =true; 
  if (condition) { 
    return <p>true</p>; 
  } else { 
    return <p>false</p>; 
  } 
} 

What are the components in React JS

Read more about JSX here

There are some differences as compared to HTML: 

  • Some attributes like class become className (because class refers to JavaScript classes), tabindex becomes tabIndex and should be written in Camel Case. 
  • We can’t return more than one HTML element at once, so make sure to wrap them inside a parent tag. 

Code:

return ( 
    <div> 
      <p>Hello</p> 
      <p>World</p> 
    </div> 
)

What are the components in React JS

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.

What is Component

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, lets 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 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 functional component. A functional component is basically a JavaScript function that returns a React element (JSX).  

Functional components start with function keyword. 

Code:

functionHelloWorld() { 
  return <h1>Hello world</h1>; 
}

What are the components in React JS

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

Code:  

constHelloWorld= () => { 
  return <h1>Hello world</h1>; 
};

What are the components in React JS

You need to export the component in order to use it somewhere else. 

Code: 

functionHelloWorld() { 
  return <h1>Hello World</h1>; 
} 
exportdefaultHelloWorld; 

What are the components in React JS

As HelloWorld is exported herewe can import this component into another file (which will be App.js in our case) and use it as shown below. 

Code:

import HelloWorld from"./HelloWorld"; 
constApp= () => { 
  return ( 
    <divclassName="App"> 
      <headerclassName="App-header"> 
        <HelloWorld /> 
      </header> 
    </div> 
  ); 
}; 
exportdefaultApp;

What are the components in React JS

In short, a functional component is a JavaScript function or ES6 function which takes props as arguments and returns a JSX. 

Components should always start with a capital letter. 

What are Class Components? 

Another type of component is a class component. Just as we have functionswe also have classes in JavaScriptClass components are ES6 classes that return JSX. The same  HelloWorld function can be converted to 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: 

classHelloWorldextendsReact.Component { 
  render() { 
    return <h1>Hello World</h1>; 
  } 
} 

What are class components

What are the uses of class components? 

Apart from returning the JSX, sometimes we have a situation where we need to manage some data inside the components; which makes the components more dynamic and makes our application faster and more user friendly. This data is called state 

We used to use class components in order to manage the stateIn the older versions of React (before version 16.8), it was not possible to use state inside functional components. 

Apart from managing the state we use class components to perform some additional operations, like life-cycle methods.  

To summarise, a class component is an ES6 class which extends a React.Component. It uses render method to return a JSX. It accepts props (inside constructor) if necessary. 

This has changed with the introduction of React Hooks, and now we can also manage state and perform life cycle methods inside functional components with hooks.  

What are Props? 

Prop is a way that components communicate. React uses props to transfer data from one component to another component. 

But remember that props only transport data in a one-way flow (only from parent to child components). It is not possible for props to pass data from child to parent, or to components at the same level. 

Now lets go back to our App component and pass props from an App to its child (HelloWorld.js in our case).  

First, we need to define a prop on the HelloWorld Component and assign a value to it. 

Code:

import HelloWorld from"./HelloWorld";
constApp= () => { 
  return ( 
    <divclassName="App"> 
      <headerclassName="App-header"> 
        <HelloWorldtitle="Hello World" /> 
      </header> 
    </div> 
  ); 
}; 

What are the components in React JS

Here we passed title as a prop to HelloWorld component and gave it a value of “Hello World” which is a string. 

Props are custom values and they also make components more dynamic.  

Since the HelloWorld component is the child here, we need to define props on its parent (App), so we can pass the values and get the result simply by accessing the prop title in the HelloWorld component as shown below. 

Code:

functionHelloWorld(props) { 
  return <h1>{props.title}</h1>; 
} 
exportdefaultHelloWorld; 

What are the components in React JS

If you save the files and start the app and look at the browser, you will find HelloWorld on the screen as shown below. 

What are the components in React JS

Now we have made the HelloWorld component more dynamic by passing our title as a prop to the component. Let’s see how we made it dynamic. 

We can use HelloWorld component more than once in our App component but with different value than our title prop, as shown below. 

Code:

import HelloWorld from"./HelloWorld"; 
constApp= () => { 
  return ( 
    <divclassName="App"> 
      <headerclassName="App-header"> 
        <HelloWorldtitle="Hello World" /> 
        <HelloWorldtitle="Hello India" /> 
        <HelloWorldtitle="Hello America" /> 
        <HelloWorldtitle="Hello China" /> 
      </header> 
    </div> 
  ); 
}; 

What are the components in React JS

Now if you save the files and reload the browser, the screen is shown as below.

What are the components in React JS

Now we are outputting different titles from the same component (HelloWorld.js) which makes the component Dynamic. 

We can do the same using class components as well. Now lets change HelloWorld.js into class component which accepts props. We can achieve that by changing the code as shown below. 

Code:  

import React from"react";  
classHelloWorldextendsReact.Component { 
  constructor(props) { 
    super(props); 
  } 
  render() { 
    return <h1>{this.props.title}</h1>; 
  } 
}  
exportdefaultHelloWorld;

What are the components in React JS

Now when you save it, you will find no change in the output you see on the screen. But this time we are using class components. 

NoteWe can access props directly upon this keyword in class components (this.props.title) and there is no need of constructor. It has been added just for the reference, and we will learn about it next. 

It's important to note that props are Read Only; that is, we cannot change the value of the props inside the child components. We can only use the props as shown in the example without changing their value. 

What is Constructor? 

In JavaScript the constructor is a method used to initialize an object's state in a class. It is automatically called during the creation of an object in a class.  

The concept of a constructor is the same in React. The constructor in a React component is called before the component is mounted. We use that to define a state object inside a class component. 

We can change our existing class component to use state and props by changing the code as shown below. 

Code:

import React from"react"; 
classHelloWorldextendsReact.Component { 
  constructor(props) { 
    super(props); 
    this.state= { 
      header:props.title, 
    }; 
  } 
  render() { 
    return <h1>{this.state.header}</h1>; 
  } 
} 

What are the components in React JS

Now if you save you will find no change in the output you see on the screen. But this time we are using state and props inside the class component. 

Sometimes when working with React, people get carried away and create too many components. This leads to deeply nested structures which make it difficult to pass props all the way down. This can be solved to an extent by using 2 techniques. 

  1. Composition 
  2. Higher Order Components 

What is Composition? 

In React, a composition is a pattern of the component model. It's how we build components from other components, of varying complexity and specialization through props. Depending on how generalized these components are, they can be used in building many other components.  

The Provider component which is provided by React Redux and Context API in React Hooks is the best example of a Composition. 

For Example:  

Here we have App.js which passes title and description as props to HelloWorld.js component. 

Code:  

import"./App.css"; 
import HelloWorld from"./HelloWorld";  
constApp= () => { 
  return ( 
    <divclassName="App"> 
      <headerclassName="App-header"> 
        <HelloWorld 
          title="Hello World" 
          description="Getting started with react" 
        /> 
      </header> 
    </div> 
  ); 
}; 
exportdefaultApp; 

What are the components in React JS

HelloWorld.js uses title prop but it does not use the description; instead, it just sends it as a prop to its child component, that is Description.js.

import Description from"./Description"; 
constHelloWorld= (props) => { 
  return ( 
    <div> 
      <h1>{props.title}</h1> 
      <Descriptiondescription={props.description} /> 
    </div> 
  ); 
}; 
exportdefaultHelloWorld;

What are the components in React JS

Description.js actually uses description which is passed from App.js. This is called prop drilling. 

This can be avoided by creating a context for our App and composing our app with the Provider component, which is provided by createContext hookand then passing our required data as an object to the provider component as shown below. 

Code:

import{ createContext } from"react"; 
import"./App.css"; 
import HelloWorld from"./HelloWorld"; 
exportconstContext=createContext();  
constApp= () => { 
  return ( 
    <Context.Provider 
      value={{ 
        title:"Hello World", 
        description:"Getting started with react", 
      }} 
    > 
      <divclassName="App"> 
        <headerclassName="App-header"> 
          <HelloWorld /> 
        </header> 
      </div> 
    </Context.Provider> 
  ); 
};  
exportdefaultApp;

What are the components in React JS

Now we can pull out our data from the context using a useContext hook, and use the required data within the components instead of passing them as props, as shown below. 

Example: In HelloWorld.js we pull out the title as we only need that in this component. 

Code: 

import{ useContext } from"react"; 
import Description from"./Description"; 
import{ Context } from"./App"; 
constHelloWorld= () => { 
  const{ title } =useContext(Context); 
  return ( 
    <div> 
      <h1>{title}</h1> 
      <Description /> 
    </div> 
  ); 
}; 
exportdefaultHelloWorld;

What are the components in React JS

Example:In HelloWorld.js we pull out the description as we only need that in this component. 

Code: 

import{ useContext } from"react"; 
import{ Context } from"./App"; 
constDescription= (pops) => { 
  const{ description } =useContext(Context); 
  return <p>{description}</p>; 
}; 
exportdefaultDescription; 

What are the components in React JS

If you observe in the above code, the components are not taking any props but are still getting access to all the dataas we have Composed our App component with the Provider component from context. This helps in less prop drilling, and cleaner and readable code. 

Higher Order Components: 

Higher Order Components are JavaScript functions used for adding additional functionalities to the existing component. These functions are pure, which means they are receiving data and returning values according to that data. If the data changes, higher order functions are re-run with different data inputs. 

Higher Order Component (HOC) is wrapping around "normal" component and providing additional data input. It is actually a function that takes one component and returns another component that wraps the original one. 

Now let's try to rewrite the App we used all this time using Higher Order Components. 

Let's create a Higher Order Component  MyHOC.js which takes component and returns a component as shown below. 

Code: 

constMyHOC= (Component) => (props) => { 
  constdescription="Getting started with react"; 
  return <Componentdescription={description}{...props} />; 
}; 
exportdefaultMyHOC; 

What are the components in React JS

Here our Higher Order Component returns a component. However, by enhancing its properties in this case we pass additional data (description) as prop, along with the props which are passed to the component. 

Now we can pass our HelloWorld.js to this Higher Order Component as shown below. 

Code:

importMyHOCfrom"./MyHOC"; 
constHelloWorld= (props) => { 
  return ( 
    <div> 
      <h1>{props.title}</h1> 
      <p>{props.description}</p> 
    </div> 
  ); 
};  
exportdefaultMyHOC(HelloWorld);

What are the components in React JS?What are the components in React JS

Here we wrap the Helloworld.js within the Higher Order Component that we just created; but we can use the description prop passed by MyHOC component which is a Higher Order ComponentWe can avoid prop drilling, and add many other properties to other components using Higher Order Components. 

What have you learnt? 

We have learnt about the two types of components in React; functional and class components. We learnt about extraction of components and how to reuse the components. After that, we went on to learn about props: how to pass them and use them inside the child components. We understood what prop drilling is, and have seen how to avoid prop drilling by using composing method and Higher Order Components.  

If you are aspiring to be a React developer, these are basic concepts that you should thoroughly understand, before moving on to more complex code. 

Profile

KnowledgeHut

Author
KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.