How to create components in React

How to create components in React

Preface

In this section we will introduce the types of components in React and how to create and use components.

This article will introduce you to the following:

  • Creating a Class Component
  • Creating a Function Component
  • Rendering Components
  • Synthetic Components
  • Extracting components
  • Props are read-only

Component Introduction

Components allow you to divide your user interface into independent, reusable widgets and design each widget individually.

By definition, components are like JavaScript functions. Components can receive arbitrary input (called "props") and return React elements that describe what to display on the screen.

Props, that is, property, is written as props in the code, so props can be used to refer to properties.
There are two types of components in react: class components and function components

Creating a Class Component

The definition of a class component has the following requirements:

  • Class components need to inherit from React.Component
  • Class components must implement the render function

Before ES6, class components could be defined using the create-react-class module, but the official website currently recommends that you use ES6 class definitions.

Use class to define a component:

class App extends Component {
  constructor() {
    super()
    this.state = {}
  }

  render() {
    return <h2>Hello App</h2>
  }
}

Let's analyze in detail the parts of the class component.

  • Constructor: This is the constructor of the class component. It is optional. We usually initialize some data in the constructor.
  • this.state: We add a state property to the class component in the constructor. You can understand it as a state object in the component, which contains various properties for maintaining the data inside the component. At the same time, you can access the property through this.state.<property name>;
  • render(): This method is the only method that must be implemented in a class component. The class component returns the display content of the component through render();

About state

We can add data objects to class components through this.state, and we can access the properties in our setState through this.state.<property name>.

constructor(props) {
    super(props);
    this.state = {
      name:"xhs-rookies"
    }
  }

render(){
    return <h2>{this.state.name}</h2>
  }

However, if we want to modify the name attribute in the above example, we must use the setState() method specified by react to add or modify the value in the state.

this.state.name = 'new xhs-rookies' //Wrong way, not allowed this.setState({ name: 'new xhs-rookies' }) //Correct way

To put it simply, in react, the page is rendered based on data. Using setState() to update the data, react will help us execute render() to update the page, thereby updating all the data used in the state on the page.

About Render

When render is called, it checks the changes of this.props and this.state and returns many types. Many times we choose to let this method return a React element, and then let React render and display it:

React Elements:

  • Typically created via JSX.
  • For example, <div/> will be rendered as a DOM node by React, and <MyComponent/> will be rendered as a custom component by React;
  • Both <div/> and <MyComponent/> are React elements.

For more information about the render() method, see React.Component - Render)

Creating a Function Component

A function component is a function defined using function, but this function returns the same content as the render function in a class component.

Compared with class components, function components have their own characteristics:

  • There is no life cycle, it will be updated and mounted, but there is no life cycle function;
  • There is no this (component instance);
  • No internal state;

Let's define a function component:

export default function App() {
  return <div>xhs rookies</div>
}

Rendering Components

In the previous articles, we only encountered React elements that represented DOM tags:

const element = <div />

However, elements can also represent user-defined components:

const element = <Welcome name="xhs rookies" />

When React encounters an element representing a user-defined component, it passes the JSX attributes to the corresponding component in a separate object. We'll call this the "props" object.

For example, the following code renders "xhs rookies" on the page:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>
}

const element = <Welcome name="xhs rookies" />
ReactDOM.render(element, document.getElementById('root'))

Let's briefly explain the above example:

  • We called the ReactDOM.render() method and passed it the <Welcome name="xhs rookies" /> element.
  • React calls the Welcome component and passes it {name: 'xhs rookies'} as the props object.
  • The Welcome component returns <h1>xhs rookies</h1>.
  • React DOM quickly updates the DOM to display <h1>xhs rookies</h1>.

Note: Component names always start with a capital letter.

For example, <div/> represents a DOM tag, while <Welcome/> represents a component and requires a Welcome component in the scope.

You can read more about the reasoning behind this in Dive into JSX.

Synthetic Components

Components can reference other components in their output. This allows us to use the same components at any level of abstraction. A button, a form, a dialog, a screen: in a React application, all of these are usually described as components.

For example, we can create an App component and render Welcome multiple times inside it:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>
}

function App() {
  return (
    <div>
      <Welcome name="rookie-Sara" />
      <Welcome name="rookie-Cahal" />
      <Welcome name="rookie-Edite" />
    </div>
  )
}

 
ReactDOM.render(<App />, document.getElementById('root'))

Typically, new React apps have a single top-level App component. However, if you integrate React into an existing application, you may need to start from the bottom up, starting with small components like Button and gradually integrating it to the top level of the view layer.

Extracting components

Don't be afraid to break a component into multiple smaller components.

For example, consider the Comment component:

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <img className="Avatar" src={props.author.avatarUrl} alt={props.author.name} />
        <div className="UserInfo-name">{props.author.name}</div>
      </div>
      <div className="Comment-text">{props.text}</div>
      <div className="Comment-date">{formatDate(props.date)}</div>
    </div>
  )
}

It accepts author (an object), text (a string), and date (a date) as props.

This component is difficult to modify because it is nested and it is difficult to reuse parts of it. Let's extract some components from it.

First, extract the avatar:

function Avatar(props) {
  return <img className="Avatar" src={props.user.avatarUrl} alt={props.user.name} />
}

The Avatar component doesn't care how it is rendered in a Comment. This is why we gave its prop a more general name: user, rather than author.

We recommend naming props from the perspective of the component itself rather than the context in which it is used.

We can simplify the Comment component a bit:

function Comment(props) {
  return (
    <div className="Comment">
      <div className="UserInfo">
        <Avatar user={props.author} />
        <div className="UserInfo-name">{props.author.name}</div>
      </div>
      <div className="Comment-text">{props.text}</div>
      <div className="Comment-date">{formatDate(props.date)}</div>
    </div>
  )
}

Next, we extract the UserInfo component, which is used to display the Avatar next to the username:

function UserInfo(props) {
  return (
    <div className="UserInfo">
      <Avatar user={props.user} />
      <div className="UserInfo-name">{props.user.name}</div>
    </div>
  )
}

This allows us to simplify the Comment component further:

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo user={props.author} />
      <div className="Comment-text">{props.text}</div>
      <div className="Comment-date">{formatDate(props.date)}</div>
    </div>
  )
}

Extracting components may seem like a tedious task, but in large apps what it can reward us is a large number of reusable components. A good rule of thumb is that if part of your UI is used multiple times (Button, Panel, Avatar), or is complex enough (App, FeedStory, Comment), it’s best to make it a reusable component.

Props are read-only

Whether you declare a component as a function or a class method, it cannot modify its own props. Consider the following sum function:

function sum(a, b) {
  return a + b
}

Such functions are called "pure functions" because they do not attempt to change their inputs and always produce the same results for the same inputs.

On the other hand, the following is an impure function because it mutates the value of its input:

function withdraw(account, amount) {
  account.total -= amount
}

Although React is flexible, it has one strict rule:

Note: All React components must be pure functions and are prohibited from modifying their own props.
Of course, application UI is always dynamic and can change at any time.

If we want to change the UI dynamically, then it involves the state we mentioned above. We render the entire page by dynamically changing the state, which we will mention later. For details, see In-depth Understanding of setState

This is the end of this article about how to create components in React. For more content about creating components in React, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React method to create a singleton component
  • Three ways to create components in React and their differences
  • In-depth understanding of the method of creating component this in es6 in React
  • Summary of React's way of creating components

<<:  Tutorial on upgrading from Centos7 to Centos8 (with pictures and text)

>>:  Detailed explanation of how to migrate a MySQL database to another machine

Recommend

Detailed explanation of the solution to the nginx panic problem

Regarding the nginx panic problem, we first need ...

How to view and configure password expiration on Linux

With the right settings, you can force Linux user...

Analysis of two implementation methods for adding static routing in Linux

Command to add a route: 1.Route add route add -ne...

CSS3 realizes text relief effect, engraving effect, flame text

To achieve this effect, you must first know a pro...

Example of how to mosaic an image using js

This article mainly introduces an example of how ...

Vue parent component calls child component function implementation

Vue parent component calls the function of the ch...

How to set up swap partition SWAP in Linux 7.7

The Swap partition of the Linux system, that is, ...

SQL function to merge a field together

Recently, I need to query all the fields in a rel...

MySQL database implements MMM high availability cluster architecture

concept MMM (Master-Master replication manager fo...

Detailed explanation of single-row function code of date type in MySQL

Date-type single-row functions in MySQL: CURDATE(...

Mac node deletion and reinstallation case study

Mac node delete and reinstall delete node -v sudo...

JavaScript function encapsulates random color verification code (complete code)

An n-digit verification code consisting of number...

Solutions to problems using addRoutes in Vue projects

Table of contents Preface 1. 404 Page 1. Causes 2...