<Modal>
<Modal.Header title="Title"/>
<Modal.Body>
<div>The body</div>
</Modal.Body>
</Modal>
What is this type of React component composition model called and how would you set up the file structure / export statements of Modal, Modal.Header, Modal.Body.
There’s a default export that enables this pattern. Something like:
// index.tsx
export default {Modal, Header, Body}
2
Answers
The pattern you’re referring to is known as the Compound Component Pattern. This pattern allows you to create a parent component (in this case,
Modal
) and define child components (Modal.Header
,Modal.Body
, etc.) that can be used within the parent. It’s a way to share implicit state and behavior among components.Here’s how you might structure your files and exports:
And then in your
index.tsx
file, you would import these components and export them as properties of theModal
object:This allows you to use the components in the way you’ve shown in your example. The
Modal
,Modal.Header
, andModal.Body
components are all accessible from theModal
export. This pattern is commonly used in libraries likereact-bootstrap
.its a compound component design where you can design various sub components and use them with . operator when exported them from a single index page where all the individual components are called from.
you can find folder structure below