React – Components

Components are one of the main features of React. Everything we build in React is a component. You can pass data to a component and nest one component into another. Working with components is the daily job of a React developer. Understanding it well is very important.

Understanding Components

In react, everything that you see is considered a component.

Image source reactjs.org

A component is a building block of a user interface. Each component has its properties, methods, state, and styling. It is an encapsulated piece of code that is hidden from the other components.

A good analogy to components is how classes and objects are created. Like a class, a component can have methods, event listeners, and other internal data (state).

We can group up one or many different elements to form a component. There is no specification or rule on how you compose your components.

Benefits of using Components

Components are the most important feature that comes with a framework like React. They offer several benefits. Here are some of them:

1. Reusability of UI code and logic.

You can reuse the same component and render different data in each of them. The example below is from the Udemy e-learning website that uses React. Here, every component has its own set of functions and capabilities that are separate from other components.

You need to define a component once, and then it can be used anywhere multiple times to render different datasets.

Image source udemy.com

2. Scalability

When an application grows, there will be hundreds of UI elements. By using components, you can build large and complex interfaces that are very useful to user interaction.

It is easy to maintain and debug React Components as you don’t have to do tricky DOM manipulation for every browser event. You only need to worry about how React should render the component when a specific condition or event occurs.

Creating a React Component

We can create a react component using two methods:

  • By using ES6 classes and extending the React.Component class.
  • Or, by using a function that returns some JSX code.

Each of the methods has its advantages and disadvantages. Before we create any component, it is helpful to know the syntax rules when creating a component.

Component Syntax Rules

  1. Component names must always start with an uppercase letter.
  2. A component can be defined by using classes or functions, and it is rendered just like any other JSX tag.
  3. A component must return only a single JSX element. You cannot return something like this:
return (
 <h1>Hello world</h1>
 <p>Some Text</p>
)

It must be wrapped inside a single parent as below:

return (
 <div>
 <h1>Hello world</h1>
 <p>Some Text</p>
 </div>
)

Optionally you can use React Fragments <> and </> if you don’t want to introduce new tags to the DOM which will serve both purposes.

return (
 <>
 <h1>Hello world</h1>
 <p>Some Text</p>
 </>
)

Class Components

React has a built-in class named React.Component that we can extend to create our class components. Using the ES6 classes, we can use OOP features like constructors, methods, and inheritance in our class components.

Taking the first step

To create a class component, we need to first import the react library.

import React from 'react'

We can now access the component API class that is a property of the React Library using React.Component. Using the class definition of ES6, we need to create a component by extending React.Component.

class App extends React.Component {
}

Here App is our component class. Notice that its first letter is an upper case as it is a component. But to display something on rendering this component, we need to code our JSX template. It is done by defining the render() method of React.Component.

class App extends React.Component {
    render() {
        return ( 
           <div>
            <h1>Class Components</h1> 
            <p> Our first component </p> 
           </div>
        )
    }
}

Now, our App is a component and can be exported and rendered to the ReactDOM as  <App />.

export default App

Why inherit the React.Component?

It is necessary to inherit/extend React.Component, so that proper functionality with the essential properties, methods are available to our class component. Examples include using constructors(), props, state, render(), and various lifecycle methods necessary for every class component.

Methods in Class Components

A method is just a function that belongs to a class. We can define various methods and use them inside our render logic to simplify our work. Methods are commonly used as event handlers.

class App extends React.Component {
    add(a, b) {
        return a + b;
    }
    render() {
        const a = 2, b = 3;
        return ( 
             <h2> Sum of {a} and {b} is { this.add(a, b)} < /h2>
        )
    }
}

We can access the methods inside our class component using the keyword this in javascript. Since JSX are just expressions, we can output variables and expressions inside the curly braces.

Since render() is a function, after all, so we can define variables and use them in our JSX expressions.

More into the Render Method

The render() function is a special method invoked by React every time our component updates. When a component’s state and prop changes, React starts running the render() method to keep the UI in sync with the data.

React uses virtual DOM behind the scenes, and rendering doesn’t always update the actual DOM every time.

Functional Components

Functional components are more straightforward and perfect for beginners in understanding components. Instead of defining a class, we define a function with a component name and then return some JSX that we want to render.

function App() {
    const num = 5;
    return ( <div>
        <h1>Functional Components </h1> 
        <p>They are awesome… {num} </p> 
        </div>
    )
}

They are simpler as you don’t have to understand classes, inheritance, or this keyword.

Instead of writing methods as we did in class components, we can define inner functions and use them in functional components. Rules for components still apply whether you create a functional or a class component.

A Practical Example

Following this example will give you a good idea of how components are rendered and composed to create more complex UIs. We will try to break down the UI in the image into components. React always recommends to think an interface in terms of components.

First, we will create the User component, which will render two users. At last, Users will be rendered in the App component.

So, for that, create a folder named components inside the src folder. Make sure you have created your project using the “Create React App” CLI tool. Storing the component files inside the folder “components” is a standard pattern, and it helps us organize our code.

Now create two files, User.js and Users.js. These files have been named in uppercase as they are components. Remember that naming a file is just a convention. The code structure should look like the screenshot below.

First, we have to design the User component. So, go to User.js and add this code:

import React from 'react'
class User extends React.Component {
    render() {
        return ( <div>
                 <h3> User Account </h3> 
                 <p> Name: { this.props.name} </p> 
                 <p> Age: { this.props.age
            } </p> 
                 <button>Message</button> 
                 <button>Subscribe</button> 
                 </div>
        )
    }
}
export default User

We have used props, which you can ignore for now if you don’t understand. It’s just a way to pass data to components. Now, we can go to Users.js where we will render multiple User components.

import User from './User'

function Users() {
    return ( <>
        <User name = 'John Doe' age = '35' / >
        <User name = 'Abhraham' age = '50' / >
        </>
    )
}
export default Users

When you use a functional component, it is not necessary to import React unless you need the React library to use some other features. We have imported the User component in this file and then rendered them with different attributes (called props). The empty tags <>, </> are called React Fragments and are used to group elements together.

Now, the last step is to go to the App component and render the Users.

import React from 'react'
import Users from './components/Users'
class App extends React.Component {
    render() {
        return ( <div>
                 <h1>List of users</h1> 
                 <hr / >
                 <Users / >
                 </div>
        )
    }
}
export default App

This is where the power of composition comes into play. The Users component renders multiple User components, but it simplifies the code into a single line.

Finally, make sure that our app Component is rendered by ReactDOM, which will display everything in the App component to the DOM.

import ReactDOM from 'react-dom'
import App from‘. / App’
ReactDOM.render( < App / > , document.getElementById('root'))

You should now see the two users in your browser after running npm start in your terminal.

Summary

Components are reusable and composable UI code. We can create components using classes (class components) or functions (functional components). Both have their pros and cons. But we need to keep some rules in mind when creating a component. Components are extremely useful in building scalable and complex UIs and making them maintainable.

Back to: React Tutorial > Learn React

Leave a Reply

Your email address will not be published. Required fields are marked *