DEV Community

Cover image for ReactJS Design Pattern ~Compound Component Pattern~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Design Pattern ~Compound Component Pattern~

・Compound Component pattern allows you to create a set of components that work together but can be composed in different ways. This pattern provides flexibility by letting users arrange sub-components in different orders while maintaining the overall functionality.

import { createContext, useContext } from "react";

const PostContext = createContext();

const usePost = () => {
  const post = useContext(PostContext);
  return post;
};

function PostCard({ post, children }) {
 return  <PostContext.Provider value={post}>{children}</PostContext.Provider>;
}

PostCard.Header = function PostCardHeader() {
  const post = usePost();
  return <h2>{post.title}</h2>;
};

PostCard.Body = function PostCardBody() {
  const post = usePost();
  return <p>{post.content}</p>;
};

PostCard.Footer = function PostCardFooter() {
  const post = usePost();
  return <p>{post.author}</p>;
};

function App() {
  const post = {
    title: "My Post",
    content: "This is the content of my post",
    author: "John Doe",
  };

  return (
    <div>
      <h1>Compound Components Pattern</h1>

      <PostCard post={post}>
        <PostCard.Header />
        <PostCard.Body />
        <PostCard.Footer />
      </PostCard>

      <PostCard post={post}>
        <PostCard.Body />
      </PostCard>
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Top comments (0)