・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...
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...