How to develop Reusable Bootstrap-like Components

Viewed 214

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!

2 Answers

Yes, it's a little bit tricky but here I am.

Layout.js

import "./layout.css";

const Layout = ({ children }) => {
  return <section>{children}</section>;
};

Layout.Header = ({ children }) => <header>{children}</header>;

Layout.Body = ({ children }) => <main>{children}</main>;

Layout.Footer = ({ children }) => <footer>{children}</footer>;

export default Layout;

App.js

import Layout from "./Layout";

export default function App() {
  return (
    <div className="App">
      <Layout>
        <Layout.Header>Header goes here</Layout.Header>
        <Layout.Body>Body goes here</Layout.Body>
        <Layout.Footer>Footer goes here</Layout.Footer>
      </Layout>
    </div>
  );
}

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>
Related