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

Splitting Components — Props and Event Callbacks

Splitting Components — Props and Event Callbacks

Componentization is the most core design idea of React. In this chapter you will learn to split pages into reusable small components and implement parent-child communication through Props and callback functions.


Why Split Components?

App.jsx keeps getting longer, with hundreds of lines crammed together, making it hard to maintain and reuse.

The principle of splitting components: each component is responsible for only one thing, and they are combined to accomplish complex features.

What Granularity Is Appropriate?

Page Area Should It Be a Component? Reason
Navigation bar Is Needed on every page; independent functionality
Article card Is Every item in the list has the same structure
Category filter button group Is Has its own state and interactions
Simple wrapper container No Only for layout, no independent behavior

Parent to Child: Props

In React, Props are the parameters of a function - when a parent component calls a child component, it passes data in through attributes.

Example

// File path: src/components/BlogCard.jsx

// Props are the first parameter of the function, usually used via destructuring

function

BlogCard

(

{

title

,

summary

,

date

,

category

}

)

{

 

return

(

   

<

div className

=

"card"

     

<

span className

=

"tag"

{

category

}

span

     

<

h3

{

title

}

h3

<

p

{

summary

}

p

<

span className

=

"date"

{

date

}

span

   

div

 

)

}

export

default

BlogCard

The parent component passes data in just like writing HTML attributes:

Example

// File path: src/App.jsx

import

BlogCard from

'./components/BlogCard'

function

App

(

)

{

 

const

articles

=

[

   

{

id

:

1

,

title

:

'React Getting Started'

,

summary

:

'Learn React from Scratch'

,

date

:

'2024-05-10'

,

category

:

'React'

}

,

   

{

id

:

2

,

title

:

'Promise Explained in Detail'

,

summary

:

'Understanding Asynchrony'

,

date

:

'2024-05-08'

,

category

:

'JavaScript'

}

,

 

]

 

return

(

   

<

div className

=

"article-grid"

     

{

articles.

map

(

article

=>

(

       

<

BlogCard

key

=

{

article.

id

}

          title

=

{

article.

title

}

          summary

=

{

article.

summary

}

          date

=

{

article.

date

}

          category

=

{

article.

category

}

       

/>

     

)

)

}

   

div

 

)

}

Props areOne-Way Data Flow: data flows from parent to child components. A child component cannot modify the Props it receives. If modification is needed, it should be handled by the parent through a callback function.


Child to Parent: Callback Functions

When a child component needs to notify the parent that 'something happened', the parent needs to pass a callback function as a Prop.

Example

// File path: src/components/CategoryFilter.jsx

function

CategoryFilter

(

{

categories

,

activeCategory

,

onCategoryChange

}

)

{

 

return

(

   

<

div className

=

"filter-bar"

     

{

categories.

map

(

cat

=>

(

       

<button key={cat}className={activeCategory===cat?'active'>

:

''

}

         

// On click, call the callback function passed from the parent

          onClick

=

{

(

)

=>

onCategoryChange

(

cat

)

}

       

         

{

cat

}

       

button

     

)

)

}

   

div

 

)

}

export

default

CategoryFilter

The parent component passes the callback function:

Example

import

{

useState

}

from

'react'

import

CategoryFilter from

'./components/CategoryFilter'

function

App

(

)

{

 

const

[

activeCategory

,

setActiveCategory

]

=

useState

(

'All'

)

 

const

categories

=

[

'All'

,

'React'

,

'JavaScript'

,

'CSS'

]

 

// Callback function: responds to the child component's click event

 

function

handleCategoryChange

(

cat

)

{

    setActiveCategory

(

cat

)

 

}

 

return

(

   

<

CategoryFilter

categories

=

{

categories

}

activeCategory

=

{

activeCategory

}

onCategoryChange

=

{

handleCategoryChange

}

/>

)

}

Vue3 uses the emit mechanism, React uses callback functions - the essence is the same, only the syntax differs.


Props Destructuring and Default Values

Example

// Props with default values

function

BlogCard

(

{

  title

=

'Untitled Article'

,

       

// ES6 destructuring default values

  summary

=

'No summary yet'

,

  date

=

''

,

  category

=

'Uncategorized'

}

)

{

 

return

(

   

<

div className

=

"card"

     

<

span className

=

"tag"

{

category

}

span

     

<

h3

{

title

}

h3

<

p

{

summary

}

p

{

date

&&

<

span className

=

"date"

{

date

}

span

}

   

div

 

)

}


Hands-On: Extract Three Components

The component structure of the blog project is as follows:



src/

├── components/

│   ├── NavBar.jsx       # 顶部导航栏

│   ├── BlogCard.jsx     # 单篇文章卡片

│   └── CategoryFilter.jsx  # 分类筛选按钮组

└── App.jsx

NavBar.jsx

Example

// File path: src/components/NavBar.jsx

import

'../App.css'

function

NavBar

(

)

{

 

return

(

   

<

header className

=

"navbar"

     

<

a href

=

"/"

className

=

"logo"

RUNOOB Blog

a

     

<

nav

<

a href

=

"/"

Home

a

       

<

a href

=

"#"

About

a

     

nav

   

header

 

)

}

export

default

NavBar

App.jsx — integrates all components

Example

// File path: src/App.jsx

import

{

useState

,

useMemo

}

from

'react'

import

NavBar from

'./components/NavBar'

import

BlogCard from

'./components/BlogCard'

import

CategoryFilter from

'./components/CategoryFilter'

import

'./App.css'

function

App

(

)

{

 

const

[

articles

]

=

useState

(

[

   

{

id

:

1

,

title

:

'Complete Guide to React Getting Started'

,

summary

:

'Learning React Hooks from Scratch'

,

date

:

'2024-05-10'

,

category

:

'React'

}

,

   

{

id

:

2

,

title

:

'JS Asynchronous Programming Explained'

,

summary

:

'Understanding Promise and async/await'

,

date

:

'2024-05-08'

,

category

:

'JavaScript'

}

,

   

{

id

:

3

,

title

:

'CSS Grid Layout in Practice'

,

summary

:

'Responsive Layout with Grid'

,

date

:

'2024-05-05'

,

category

:

'CSS'

}

,

   

{

id

:

4

,

title

:

'React Hooks in Depth'

,

summary

:

'Deep Understanding of useState and useEffect'

,

date

:

'2024-05-03'

,

category

:

'React'

}

,

   

{

id

:

5

,

title

:

'Complete Guide to Flexbox'

,

summary

:

'Learn Flexbox Layout in One Article'

,

date

:

'2024-05-01'

,

category

:

'CSS'

}

,

 

]

)

 

const

[

activeCategory

,

setActiveCategory

]

=

useState

(

'All'

)

 

const

categories

=

useMemo

(

(

)

=>

{

   

const

cats

=

articles.

map

(

a

=>

a.

category

)

   

return

[

'All'

,

...

new

Set

(

cats

)

]

 

}

,

[

articles

]

)

 

const

filteredArticles

=

useMemo

(

(

)

=>

{

   

if

(

activeCategory

===

'All'

)

return

articles

   

return

articles.

filter

(

a

=>

a.

category

===

activeCategory

)

 

}

,

[

articles

,

activeCategory

]

)

 

return

(

   

<

div className

=

"app"

     

<

NavBar

/>

<

main className

=

"container"

       

<

h2 className

=

"section-title"

Latest Articles

h2

       

{

/* Child component: receives props (categories, activeCategory) and callback (onCategoryChange) */

}

       

<

CategoryFilter

categories

=

{

categories

}

activeCategory

=

{

activeCategory

}

onCategoryChange

=

{

setActiveCategory

}

/>

<

p className

=

"result-info"

Total

{

filteredArticles.

length

}

articles

p

       

{

filteredArticles.

length

===

0

?

(

         

<

p className

=

"empty-tip"

No articles in this category yet

p

       

)

:

(

         

<

div className

=

"article-grid"

           

{

filteredArticles.

map

(

article

=>

(

             

<

BlogCard

key

=

{

article.

id

}

                title

=

{

article.

title

}

                summary

=

{

article.

summary

}

                date

=

{

article.

date

}

                category

=

{

article.

category

}

             

/>

           

)

)

}

         

div

       

)

}

     

main

     

<

footer className

=

"footer"

       

<

p

©

2024

RUNOOB Blog.

Powered

by React.

p

     

footer

   

div

 

)

}

export

default

App


Chapter Summary

In this chapter you mastered the core of React component communication: parent to child via Props (function parameters), child to parent via Props callback functions.

The blog project's three components NavBar, BlogCard, and CategoryFilter are in place, and the code structure is much clearer.