Skip to content

Instantly share code, notes, and snippets.

@vv13
Created December 31, 2021 07:18
Show Gist options
  • Save vv13/73f83b2361546c27e566dc30e9133b71 to your computer and use it in GitHub Desktop.
Save vv13/73f83b2361546c27e566dc30e9133b71 to your computer and use it in GitHub Desktop.
React Compose Components.
import React from 'react';
const genContainer =
(name: string): React.FC =>
({ children }) =>
(
<div>
<h1>I'm {name}</h1>
<div style={{ paddingLeft: '10px' }}>{children}</div>
</div>
);
const Compose: React.FC<{
components: React.ComponentType[];
children: React.ReactElement;
}> = ({ children, components }) =>
components.reduceRight(
(Child, Parent) => (
<>
<Parent>{Child}</Parent>
</>
),
children,
);
export default () => {
return (
<Compose
components={['parent1', 'parent2', 'parent3', 'parent4'].map((name) => genContainer(name))}
>
<h1>Bingo!</h1>
</Compose>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment