SoFunction
Updated on 2025-04-07

How to create components in React

Preface

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

This article will introduce you to the following:

  • Create a class component
  • Create function components
  • Rendering components
  • Synthetic components
  • Extract components
  • Props are read-only

Component introduction

Components allow you to split the user interface into separate, reusable widgets and can design each component separately.

By definition, components are like JavaScript functions. Components can receive any input (called "props") and return a React element to describe the content displayed on the screen.

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

Create a class component

The definition of a class component has the following requirements:

  • Class components need to be inherited from
  • The class component must implement the render function

Before ES6, class components can be defined through the create-react-class module, but the official website currently recommends that we use the class class definition of ES6.

Use class to define a component:

class App extends Component {
  constructor() {
    super()
     = {}
  }

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

Let's analyze in detail what parts of the class components are.

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

About state

We can add data objects to the class component, and we can access the properties in our setState through .<attribute name>.

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

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

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

 = 'new xhs-rookies' //Incorrect method, no use({ name: 'new xhs-rookies' }) //The correct way

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

About render

When render is called, it checks for changes in and returns many types. Many times we choose to let the method return the React element and then hand it over to React for rendering and displaying:

React elements:

  • Usually created through 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 details about the render() method, please see - Render)

Create function components

Function components are functions defined using function, but this function will return the same content as the render function in the class component.

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

  • There is no life cycle, it will also be updated and mounted, but there is no life cycle function;
  • No this (component instance);
  • There is 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 representing the DOM tag:

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 as a separate object. We call it "props" object.

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

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

const element = <Welcome name="xhs rookies" />
(element, ('root'))

Let's briefly explain the above example:

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

Note: Component names always start with capital letters.

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 reasons behind this in JSX.

Synthetic components

Components can refer to other components in their output. This allows us to use the same components to abstract to any level. A button, a form, a dialog, a screen: In React applications, 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, {}</h1>
}

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

 
(<App />, ('root'))

Typically, new React apps have a separate top-level app component. However, if you integrate React in your existing application, you can need to gradually integrate it into the top layer of the view layer from bottom to top, starting with widgets like Button.

Extract components

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

For example, think about the following Comment component:

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

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

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

First, extract the avatar Avatar:

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

The Avatar component doesn't have to care about how it renders in Comment. This is why we have a more general attribute name for prop: user, not author.

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

We can simplify the Comment component a little bit:

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

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

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

This allows us to simplify the Comment component further:

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

Extracting components may seem like a tedious job, but what you can reward us with large apps is a large number of reusable components. A good scrutiny is if you need to use a part of your UI multiple times (Button, Panel, Avatar), or it is complex enough (App, FeedStory, Comment), the best way to do it is to make it a reusable component.

Props are read-only

No matter you declare a component using a function or class method, it cannot modify its own props. Think about the following sum (sum) function:

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

This function is called "Pure functions” because they do not try to change their input, and for the same input, the same result can always be obtained.

Instead, the following is a non-pure function because it changes its own input value:

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

Although React is flexible, it has a strict rule:

Note: All React components must be pure functions and prohibit modification of their own props.
Of course, the application UI is always dynamic and can be changed at any time.

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

This is the end of this article about how React creates components. For more related content on React, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!