17.2 C
New York

Guide to React Component

Date:

Introduction

A component is the probably most important concept to understand in React. It is one of the core building blocks of React that allows us to split a UI into independent, reusable pieces, making the task of building UIs much easier. All of these independent components are then combined into a parent component, which will serve as our final user interface.

In this guide, we will take a look at components and how they work in React, we will also see how to pass data from one component to another using props.

What Is a Component?

A component is a self-contained, reusable code block that divides the user interface into smaller pieces rather than building the entire UI in a single file. Buttons, forms, dialog, and so on can all be expressed as components. React components accept arbitrary inputs (“props”) and return React elements or JSX code that tells what should be rendered on the screen.

To demonstrate how components work, we have broken down the UI of an example Todo Application into individual components:

This Todo Application is made up of four different components which help make the code easier to understand and maintain. When building larger applications we can end up with many components, so it’s crucial to have well-structured and readable code.

Note: Widely accepted convention states that all component names must start with a capital letter.

Types of Components in React

In React, there are primarily two types of components – Functional and Class components.

Functional Components

This is the simplest way to create a component, it is the first and recommended component type in React. A functional component is basically a JavaScript/ES6 function that returns a special JavaScript syntax called JSX or React element. The function below is a valid functional component that receives an object of properties, usually named props.

function Introduction(props) {
    return <h1>Hello, I am {props.name}</h1>;
}

Alternatively, we can also create a functional component using the arrow function notation:

const Introduction = (props) => {
    return <h1>Hello, I am {props.name}</h1>;
}

Note: Essentially, this is just another JavaScript function. What differentiates it from other, usual, functions is its return value – the JSX (JavaScript XML) formatted code.

Class Components

The component class is an ES6 class that extends React component class and must have a render() method that returns JSX. It accepts props in the constructor if necessary.

It is the second type of component and was mostly used because “state” could not be used inside functional components in older versions of React (prior to 16.8). As a result, functional components were only used for UI rendering, whereas class components were used for data management and some additional operations such as life-cycle methods, and so on. However, with the introduction of React hooks, this has changed, and we can now use states in functional components as well.

Below, is the same Introduction component, but created as a class component this time:

class Introduction extends React.Component {
    render() {
        return <h1>Hello, I am {this.props.name}</h1>;
    }
}

Note: Now that we’ve created both functional and class components, compare the two – you can see that the contents are essentially the same.

Making Use of Components in React

So far, we’ve seen how to create a functional or a class component. Now, let’s take a look at how we can use these components in a parent component. To be able to use a component later (or in a parent component), we must first export it so that we can import it elsewhere:

const Introduction = (props) => {
    return <h1>Hello, I am {props.name}</h1>;
}

export default Introduction;

After importing it, we can refer to it in the parent component (in this case, the App component):

import Introduction from './Introduction';

const App = () => {
    return (
        <div className="App">
            <Introduction name="John Doe" />
        </div>
    );
}

Passing Data via Props Into Components

When we install React using the create-react-app command, we automatically get a functional component in our App.js file that serves as the starting point for our application. Most of our data will most likely reside in the App.js file when we build our applications, and we will undoubtedly want to pass this data down to the new components (children components). Props, which stands for “properties”, are used to accomplish this.

This is an important concept in React that allows components to communicate with each other. Props are read-only, so they can only transport data in one direction (from parent to child components). Props do not allow data to be passed from child to parent or from component to component at the same level.

Let’s now create a Button component, and then pass in names for different buttons as props:

const Button = (props) => {
    return (
        <div>
            <button class="btn">{props.name}</button>
        </div>
    );
};

export default Button;

Let’s go back to the App.js file and see how we can pass data to the button component using props. All we need to do is define a prop on the Button Component and assign a value to it:

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

import Button from './Button';

const App = () => {
    return (
        <div className="App">
            <h1>Hello World</h1>
            <Button name="Login" />
            <Button name="Logout" />
            <Button name="Sign Up" />
        </div>
    );
};

export default App;

Note: We have to import the component for us to make use of it in the parent component.

Guide to React Component Code CoinGenius Hosts Virtual Crypto Event The Road To Mass Adoption

Props can be used to pass any type of data, including arrays and objects, so there is no limit to what they can be used for.

Splitting up an App Into Components

Before we round-up this guide, let’s take a look at an example of a StudentInfo component that comprises the students details and score details.

const StudentInfo = (props) => {
    return (
        <div className="student">
            <div className="student-info">
                <img
                    className="Avatar"
                    src={props.student.image}
                    alt={props.student.name}
                />
                <div className="student-name-info">
                    <p>{props.student.name}</p>
                    <p>{props.student.userName}</p>
                </div>
            </div>
            <div className="score-details">
                <div className="Comment-text">{props.score}</div>
                <div className="Comment-date">{props.remark}</div>
            </div>
        </div>
    );
};

export default StudentInfo;

This takes a student object with a lot of information in it (as props) and describes a student card to display the student details alongside the student’s score and remark. Because of the nesting, this component can be difficult to change, and it is also difficult to reuse individual parts of it.

Let’s extract a component from it, and that is the StudentInfo section:

const StudentInfo = (props) => {
    return (
        <div className="student-info">
            <img
                className="Avatar"
                src={props.student.image}
                alt={props.student.name}
            />
            <div className="student-name-info">
                <p>{props.student.name}</p>
                <p>{props.student.userName}</p>
            </div>
        </div>
    );
};

export default StudentInfo;

We can now simplify the parent component to look like this:

import StudentInfo from './StudentInfo';

const StudentInfo = (props) => {
    return (
        <div className="student">
            <StudentInfo student="props.student" />
            <div className="score-details">
                <div className="Comment-text">{props.score}</div>
                <div className="Comment-date">{props.remark}</div>
            </div>
        </div>
    );
};

export default StudentInfo;

Extracting components may appear to be boring at first, but having a collection of reusable components benefits us in larger apps.

Conclusion

In this guide, we have been able to learn how components work in React, the two types of components and how to pass data from one component to another using props.

  • Coinsmart. Europe’s Best Bitcoin and Crypto Exchange.Click Here
  • Platoblockchain. Web3 Metaverse Intelligence. Knowledge Amplified. Access Here.
  • Source: https://stackabuse.com/guide-to-react-component/

This Post was originally published on Stackabuse

Related articles

spot_img

Recent articles

spot_img