ReactJS Design Pattern ~Compound Component Pattern~

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5175

    #1

    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
    {children};
    }

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

    ;
    };

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

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

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

    return (

    Compound Components Pattern


















    );
    }

    export default App;











    More...
Working...