You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
title: "How to build a simple Compound component using ReactJS hooks"
4
4
date: 2021-05-25
5
5
featuredpost: false
6
6
description: >-
7
-
This article talks about what are compound components and how to build an accordion component using the concept of compound components.
7
+
This article explains with an example what compound components in react are . How to build a compound component with a tutorial to build accordion.
8
8
keywords:
9
-
- reactjs
10
-
- Compound-components
11
-
- Hooks
12
-
- Typescript
9
+
- reactjs
10
+
- Compound-components
11
+
- Hooks
12
+
- Typescript
13
13
link: /react-compound-components
14
14
category:
15
-
- Tutorial
15
+
- Tutorial
16
16
author: Ashwin kumar
17
17
tags:
18
-
- react js
19
-
- reactjs
20
-
- typescript
21
-
- compound components
22
-
- build accordion component using compound components
18
+
- react js
19
+
- reactjs
20
+
- typescript
21
+
- compound components
22
+
- build accordion component using compound components
23
23
---
24
24
25
-
**Compound Components** are an advanced and great pattern which you can use to create the meta component. It gives your components more flexibility. It is little difficult to understand the concept initially, But believe me, if you get a hold of it you will love building the components using compound components pattern
25
+
**Compound Components** are an advanced and very useful pattern. They can be used to create meta components. They are slightly counter intuitive, but trust me, once you get a hang of it, you will love building components using the compound components pattern.
26
26
27
27
## What are compound components?
28
28
@@ -32,164 +32,165 @@ The compound components are a set of two or more components that work together t
32
32
33
33
```jsx
34
34
<select>
35
-
<option>Option1</option>
36
-
<option>Option2</option>
37
-
<option>Option3</option>
38
-
<option>Option4</option>
35
+
<option>Option1</option>
36
+
<option>Option2</option>
37
+
<option>Option3</option>
38
+
<option>Option4</option>
39
39
</select>
40
40
```
41
41
42
42
In the above example, when you click on an option in the select component, select knows which option you clicked. The select and the option share the state between them and update the selected option state on their own, we don’t need to explicitly configure them.
43
43
44
44
## Compound Components in Action
45
45
46
-
In this post, we’ll be building an Accordion component using compound components.
47
-
48
-
You can check out the [Code sandbox link](https://codesandbox.io/s/interesting-wildflower-wj3iy) for the final demo of the accordion component.
46
+
we will build an Accordion component using the compound component pattern.
49
47
50
48
The accordion component will have four components.
51
49
52
-
1.**Accordion** - The outer wrapper component of the Accordion component. This is the root component of the Accordion component.
50
+
1.**Accordion** - The outer wrapper component of the Accordion component. This is the root component of the Accordion component.
53
51
2.**AccordionItem** - The component that allows us to define each accordion item. Each AccordionItem will have its AccordionButton and AccordionPanel components.
54
52
3.**AccordionButton** - The header for the Accordion component.On clicking the accordion button will open the corresponding accordion panel.
55
53
4.**AccordionPanel** - The panel for the accordion. This will hold the content of each accordion item.
56
54
57
-
We are going to create the above mentioned components one by one and also let's see how we can create the link between them.
58
-
Let's start with Accordion component. Accordion component will wrap all other necessary components and will maintain the state that is to be shared among all the other components
55
+
We are going to create the above mentioned components one by one and also let's see how we can create the link between them.
56
+
Let's start with Accordion component. Accordion component will wrap the other components. It will also maintain shared state with other components. In this case the selected accordion item (active item)
59
57
60
58
```tsx
61
59
const Accordion:React.FC<{
62
-
children:ReactNode|ReactNode[];
60
+
children:ReactNode|ReactNode[]
63
61
className?:string
64
62
}> = ({ children, className }) => {
65
-
const [activeItem, setActiveItem] =useState("");
63
+
const [activeItem, setActiveItem] =useState("")
66
64
// function to update the active item
67
-
const changeActiveItem =useCallback(
68
-
(value)=> {
69
-
if (activeItem!==value) setActiveItem(value);
65
+
const changeActiveItem =useCallback(
66
+
value=> {
67
+
if (activeItem!==value) setActiveItem(value)
70
68
},
71
69
[setActiveItem, activeItem]
72
-
);
70
+
)
73
71
74
72
return <divclassName={className}>{children}</div>
75
73
}
76
-
```
74
+
```
77
75
78
-
we had created the accordion component, now we need to pass or share the state and the function to update the state to its children. To achieve this, we are going to use the **React Context**. If you are not familiar with React context, please refer [https://reactjs.org/docs/context.html](https://reactjs.org/docs/context.html). Iam not gonna explain about react context here, but i will give you a hint about react context.
76
+
We have created the root Accordion component. Now we need to pass down or share the state and the update state function with its children. To achieve this, we are going to use the **React Context**. If you are not familiar with React context, please refer [https://reactjs.org/docs/context.html](https://reactjs.org/docs/context.html).
79
77
80
78
> Context provides a way to pass data through the component tree without having to pass props down manually at every level.
After creating the context, we need to provide values to the context, it is done by **Context.Provider** element. The values refers to the data that is to be shared among all the components in the accordion. The **Provider** component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers.
100
+
Lets provide values to the context using the Context.Provider element. The **Provider** component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers.
In the accordion, we need to share the activeItem and changeSelectedItem to all the other components, so we are passing those two to the value of accordion context provider. Now We had built the root accordion component and also we have provided the values to the context. Let's build the remaining components and we are going to use the values consumed from the context and make the accordion component work as a whole.
127
+
In the accordion, we need to share the activeItem and changeSelectedItem to all the other components, so we are passing them to the context provider which can be obtained using the the useAccordionContext custom hook (which uses the useContext hook internally). Let's build the remaining components. We are going to use the values consumed from the context and make the accordion component work as a whole.
We have done with creating all other components. Let's see what we have done.
194
195
195
196
- In the Accordion-item, label prop is used to differentiate between different accordion items. The label prop will be required in the accordionButton and accordionPanel components, so we are adding label prop to the accordionItem children along with the other props.
@@ -204,8 +205,8 @@ import {
204
205
Accordion,
205
206
AccordionButton,
206
207
AccordionItem,
207
-
AccordionPanel
208
-
} from"./components/accordion";
208
+
AccordionPanel,
209
+
} from"./components/accordion"
209
210
210
211
exportdefaultfunction App() {
211
212
return (
@@ -238,13 +239,19 @@ export default function App() {
238
239
</AccordionItem>
239
240
</Accordion>
240
241
</div>
241
-
);
242
+
)
242
243
}
243
-
```
244
+
```
245
+
244
246
Yayyy!!! We had built the accordion component using the compound components.
245
247
246
-
We can also build the same accordion component using render props method but there are many limitations to style the inner components (AccordionButton & AccordionPanel) , we need to pass props like renderAccordionButton, buttonClassName for the AccordionButton and we need separate props for AccordionItem and also AccordionPanel.
247
-
248
-
Look at the accordion component now, it looks clean, you can style each and every component of Accordion using its respective component. In future, if you want to have buttonColour for the AccordionButton component, you can just add that prop to the AccordionButton alone and not to the outer accordion component.
248
+
We can also build the same accordion component using render props method. But there are limitations to style the inner components (AccordionButton; AccordionPanel). We will have to pass props like renderAccordionButtonfor custom button component.
249
+
250
+
The accordion component, nowlooks clean. One can style every component of the Accordion using its respective component. In future, if you want to have buttonColour for the AccordionButton component, you can just add that prop to the AccordionButton itself. Not clutter the outer accordion component.
249
251
250
-
Feel free to try it and check out the component in [code sandbox](https://codesandbox.io/s/interesting-wildflower-wj3iy). I hope you had understood the compound components and how to use them.
0 commit comments