Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

React components

React components

React components are the basic units for building React applications; you can think of a component as a reusable, independent UI unit, where each component encapsulates its own structure, styles, logic, and state.

React components are the building blocks of an application; a component can be as small as a button or as large as an entire page.

Components can be divided into:Function componentsandClass components。

Technically, a React component is a JavaScript function or class that returns a React element (usually JSX).

// 最简单的组件
function Hello() {
  return 

Hello, World!

; }

Split complex UI into a component tree:


App
├── Header
│   ├── Logo
│   └── Navigation
│       ├── NavItem
│       └── NavItem
├── Main
│   ├── Sidebar
│   └── Content
│       ├── Article
│       └── Article
└── Footer

Function components

Function components are a concise way to define components.

A function component is a JavaScript function that accepts props and returns a React element.

Basic syntax:

// 方式 1:函数声明
function Welcome(props) {
  return 

Hello, {props.name}

; } // Method 2: Arrow function const Welcome = (props) => { return

Hello, {props.name}

; }; // Method 3: Simplified syntax (single-line return) const Welcome = (props) =>

Hello, {props.name}

;

Create a simple function component:

src/Welcome.js file:

import

React from

'react'

;

// Define a function component

function

Welcome

(

props

)

{

 

return

<
h1
Hello
,
{

props.

name

}

!

h1

;

}

export

default

Welcome

;

Render this component in src/index.js:

src/index.js file:

import

React from

'react'

;

import

ReactDOM from

'react-dom'

;

import

'./index.css'

;

import

Welcome from

'./Welcome'

;

const

root

=

ReactDOM.

createRoot

(

document.

getElementById

(

"root"

)

)

;

// Render the Welcome component and pass the name property

root.

render

(

<

Welcome name

=

"World"

/>

)

;

This example shows a simple component that accepts a name property and displays "Hello, World!" on the page.


Class components

Class components are defined using ES6 class syntax and are typically used when you need to manage state or use lifecycle methods.

Basic syntax:

import React, { Component } from 'react';
class Welcome extends Component {
  render() {
    return 

Hello, {this.props.name}

; } }

Create a class component:

Example

import

React

,

{

Component

}

from

'react'

;

class

Welcome

extends

Component

{

  render

(

)

{

   

return

<
h1
Hello
,
{
this

.

props

.

name

}

!

h1

;

 

}

}

export

default

Welcome

;

Render this component in src/index.js:

Example

import

React from

'react'

;

import

ReactDOM from

'react-dom'

;

import

'./index.css'

;

import

Welcome from

'./Welcome'

;

const

root

=

ReactDOM.

createRoot

(

document.

getElementById

(

"root"

)

)

;

// Render the Welcome component and pass the name property

root.

render

(

<

Welcome name

=

"World"

/>

)

;


Test example

Next, we will encapsulate a component that outputs "Hello World!" named HelloMessage:

React example

function

HelloMessage

(

props

)

{

return

<
h1
Hello
World

!

h1

;

}

const

element

= <

HelloMessage

/>;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

element

)

;

Try it »

Example analysis:

1. We can define a component using a function:

function HelloMessage(props) {
    return 

Hello World!

; }

You can also use an ES6 class to define a component:

class Welcome extends React.Component {
  render() {
    return 

Hello World!

; } }

2、const element = for user-defined components.

Note that native HTML element names start with a lowercase letter, while custom React class names start with an uppercase letter; for example, HelloMessage cannot be written as helloMessage. Also note that a component class can contain only one top-level tag, otherwise an error will occur.

If we need to pass parameters to a component, we can use this.props objects; the example is as follows:

React example

function

HelloMessage

(

props

)

{

return

<
h1
Hello
{
props

.

name

}

!

h1

;

}

const

element

= <

HelloMessage

name

=

"

Runoob

"

/>;

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

element

)

;

Try it »

In the example above name the property is obtained via props.name.

Note that when adding attributes, the class attribute must be written as className and the for attribute as htmlFor, because class and for are JavaScript reserved words.


Composite components

We can compose a component by creating multiple components, i.e., separating the different functional points of the component.

In the following example, we implement a component that outputs a website name and URL:

React example

function

Name

(

props

)

{

return

<

h1

Website name:

{

props

.

name

}

h1

;

}

function

Url

(

props

)

{

return

<

h1

Website address:

{

props

.

url

}

h1

;

}

function

Nickname

(

props

)

{

return

<

h1

Website nickname:

{

props

.

nickname

}

h1

;

}

function

App

(

)

{

return

(

<
div
<
Name
name
=
"

Runoob Tutorial

"

/> <

Url

url

=

"

http://www.runoob.com

"

/> <

Nickname

nickname

=

"

Runoob

"

/>

div

)

;

}

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<
App
/>
)

;

Try it »

In the example, the App component uses the Name, Url, and Nickname components to output the corresponding information.


Props (Properties)

Props are the way data is passed between components, similar to function parameters.

Basic Usage


// Parent component passes props
function App() {
  return (
    
); } // Receive props in child component function Greeting(props) { return (

Hello, {props.name}!

Age: {props.age}

); }

Props destructuring


// Recommended: direct destructuring
function Greeting({ name, age }) {
  return (
    

Hello, {name}!

Age: {age}

); } // Destructuring with default values function Button({ text = "Submit", variant = "primary", disabled = false }) { return ( ); }

Props types

Props can be any JavaScript value:


function Demo() {
  const user = { name: "Alice", age: 25 };
  const numbers = [1, 2, 3, 4, 5];
  const handleClick = () => alert("Clicked!");
  return (
    This is content

} /> ); }

Children Props

Special props used to pass child content to a component:


// Method 1: using props.children
function Card(props) {
  return (
    
{props.children}
); } // Method 2: Destructuring children function Card({ children, title }) { return (
{title &&

{title}

}
{children}
); } // 使用 function App() { return (

This is the card content

); }

Props immutability

Important principle: Never modify props!


// Error: modify props
function BadComponent(props) {
  props.name = "Changed"; // 绝对不要这样做!
  return 

{props.name}

; } // Correct: treat props as read-only function GoodComponent({ name }) { const displayName = name.toUpperCase(); // 创建新值 return

{displayName}

; }

Component composition and reuse

Composite Pattern


// Base components
function Avatar({ src, alt }) {
  return {alt};
}
function UserInfo({ name, email }) {
  return (
    

{name}

{email}

); } // Combine into complex component function UserCard({ user }) { return (
); }

Container component pattern


// Container component: handling logic and state
function Panel({ title, children, collapsible = false }) {
  const [isOpen, setIsOpen] = useState(true);
  return (
    

{title}

{collapsible && ( )}
{isOpen && (
{children}
)}
); } // 使用 function App() { return (

Your settings here...

); }

Higher-order component idea (achieved through composition)


// General loading state wrapper
function WithLoading({ isLoading, children }) {
  if (isLoading) {
    return 
Loading...
; } return children; } // 使用 function UserList({ users, isLoading }) { return (
    {users.map(user => (
  • {user.name}
  • ))}
); }

Component naming conventions

Naming conventions

// 正确:大写字母开头(PascalCase)
function UserProfile() { }
function BlogPost() { }
function NavBar() { }
// Error: must start with a lowercase letter
function userProfile() { } // React 会将其视为 HTML 标签

File Naming

// 推荐的文件结构
src/
├── components/
│   ├── Button.jsx          // 或 Button.js
│   ├── UserCard.jsx
│   ├── Navigation/
│   │   ├── Navigation.jsx
│   │   ├── NavItem.jsx
│   │   └── index.js        // 导出 Navigation

Component export and import

Default exports

// Button.jsx
export default function Button({ text }) {
  return ;
}
// App.jsx
import Button from './Button';

Named export

// components.jsx
export function Button({ text }) {
  return ;
}
export function Input({ value, onChange }) {
  return ;
}
// App.jsx
import { Button, Input } from './components';

Mixed export

// Card.jsx
export default function Card({ children }) {
  return 
{children}
; } export function CardHeader({ title }) { return
{title}
; } export function CardBody({ children }) { return
{children}
; } // App.jsx import Card, { CardHeader, CardBody } from './Card';

Component design principles

1. Single responsibility principle

Each component should do only one thing.

// 不好:组件做太多事情
function UserDashboard() {
  // Get user data
  // Process form
  // Display chart
  // Handle navigation
  // ...
}
// Good: split into multiple components
function UserDashboard() {
  return (
    
); }

2. Keep components simple

Component code should not exceed 200-300 lines.

// 好:提取子组件
function ProductCard({ product }) {
  return (
    
); }

3. Use Props reasonably

Do not pass too many props.

// 不好:props 过多
function User({ name, age, email, address, phone, company, role, ... }) { }
// Good: using objects
function User({ user }) {
  const { name, age, email } = user;
  // ...
}

4. Avoid deep nesting

Excessively deep component nesting leads to the props drilling problem.

// 问题:props 需要层层传递

  
    
      
        
      
    
  

// Solution: Use Context or state management