Search code examples
reactjsnext.jsfrontendreact-bootstrapes6-modules

How to develop Reusable Bootstrap-like Components


React bootstrap and other similar bootstrap libraries provide something like

import Modal from '...';

whereas Modal can be unpacked further into:

const { Header, Title, Description } = Modal;

Although Modal itself is a wrapper component.

Sample of their use-case is as such:

<Modal someProps={someValues}>
  <Modal.Title>Some Title</Modal.Title>
  <Modal.Content>Some Content</Modal.Content>
</Modal>

How does one develop something like that?

My initial thought was something like this:

const Title = ({children}) => (<something>{children}</something>);

const Content = ({children}) => (<something>{children}</something>);

export {
  Title,
  Content,
};

====================

import Modal from '...';
--or--
import { Title, Content } from '...';

but this method will cause Modal to not be usable by itself. How does this work? Does anyone have an example?

Thanks!


Solution

  • You can make like that with this approach:

    export const Modal = ({children}) => {
     return(
      <div class="modal">{children}</div>
     )
    }
    
    export const Title = ({children}) => {
     return(
      <div class="title">{children}</div>
     )
    }
    
    export const Content = ({children}) => {
     return(
      <div class="content">{children}</div>
     )
    }
    
    // join into single object
    var _default = Object.assign(Modal, {
     Title,
     Content
    });
    
    export default _default;
    
    

    We have done 😀 Now you can use this component in both (single / separate import)

    import Modal from '...';
    --or--
    import { Modal, Title, Content } from '...';
    
    <Modal someProps={someValues}>
      <Modal.Title>Modal Title</Modal.Title>
      <Modal.Content>Some Content</Modal.Content>
    </Modal>
    --or--
    <Modal someProps={someValues}>
      <Title>Modal Title</Title>
      <Content>Some Content</Content>
    </Modal>