A helper funciton to render nested multiple components
From time to time, we need to render nested multiple components in React.
function App() {
return (
<Provider1>
<Provider2>
<Provider3>
<provider4>
<Component1 />
<Component2 />
</provider4>
</Provider3>
</Provider2>
</Provider1>
);
}
Is it possible write convert the above code to the following, which is more readable?
function App() {
return (
<NestedComponent
componentList={[Provider1, Provider2, Provider3, Provider4]}
>
<Component1 />
<Component2 />
</NestedComponent>
);
}
Yes, here is code of NestedComponent
:
import React, { PropsWithChildren } from "react";
type NestedComponentProps = {
components: React.ComponentType<PropsWithChildren>[],
children?: React.ReactNode,
};
function NestedComponent({ components, children }: NestedComponentProps) {
if (components.length === 0) {
return children || null;
}
const [CurrentComponent, ...restComponents] = components;
return (
<CurrentComponent>
<NestedComponent components={restComponents}>{children}</NestedComponent>
</CurrentComponent>
);
}