Container Components
The Container Components Pattern in React is a design pattern that use to separate the logic and the UI of a component. The container component is responsible for fetching data, managing state, and passing data to the presentational component. The presentational component is responsible for rendering the UI based on the data passed to it.
Example :
Loading ...
How to use :
export default function ContainerComponents({ children, getData }: Props) {
const [data, setData] = useState();
useEffect(() => {
(async () => {
const res = await getData();
setData(res);
})();
}, []);
return React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, {
data,
});
} else {
return child;
}
});
}
const fetchData = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
return await res.json();
};
const Example = ({ data }: any) => {
if (!data) return <p>Loading ...</p>;
return <p>{data.title}</p>;
};
export const DemoContainerComponents = () => {
return (
<ContainerComponents getData={fetchData}>
<Example />
</ContainerComponents>
);
};