skip to Main Content
<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


  1. 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:

    // Modal.tsx
    import React from 'react';
    
    const Modal = ({ children }) => {
      // Modal implementation
    };
    
    export default Modal;
    
    // ModalHeader.tsx
    import React from 'react';
    
    const ModalHeader = ({ title }) => {
      // ModalHeader implementation
    };
    
    export default ModalHeader;
    
    // ModalBody.tsx
    import React from 'react';
    
    const ModalBody = ({ children }) => {
      // ModalBody implementation
    };
    
    export default ModalBody;
    

    And then in your index.tsx file, you would import these components and export them as properties of the Modal object:

    // index.tsx
    import Modal from './Modal';
    import ModalHeader from './ModalHeader';
    import ModalBody from './ModalBody';
    
    Modal.Header = ModalHeader;
    Modal.Body = ModalBody;
    
    export default Modal;
    

    This allows you to use the components in the way you’ve shown in your example. The Modal, Modal.Header, and Modal.Body components are all accessible from the Modal export. This pattern is commonly used in libraries like react-bootstrap.

    Login or Signup to reply.
  2. 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

    • Modal
      • index.tsx
      • Header.tsx
      • Body.tsx
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search