Skip to content

Commit

Permalink
[sitecore-jss-react] Refactored withComponentFactory HOC (#1086)
Browse files Browse the repository at this point in the history
* refactored withComponentFactory enhancer

* removed consumer
  • Loading branch information
addy-pathania authored Jul 7, 2022
1 parent 5fc2e3d commit fa5e259
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions packages/sitecore-jss-react/src/enhancers/withComponentFactory.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { ComponentFactoryReactContext } from '../components/SitecoreContext';
import { ComponentFactory } from '../components/sharedTypes';
import { useContext } from 'react';

export interface ComponentFactoryProps {
componentFactory?: ComponentFactory;
Expand All @@ -12,11 +13,19 @@ export interface ComponentFactoryProps {
export function withComponentFactory<T extends ComponentFactoryProps>(
Component: React.ComponentClass<T> | React.FC<T>
) {
return function WithComponentFactory(props: T) {
return (
<ComponentFactoryReactContext.Consumer>
{(context) => <Component {...props} componentFactory={props.componentFactory || context} />}
</ComponentFactoryReactContext.Consumer>
);
};
/**
* @param {T} props - props to pass to the wrapped component
* @returns {JSX.Element} - the rendered component
*/
function WithComponentFactory(props: T): JSX.Element {
const context = useContext(ComponentFactoryReactContext);

return <Component {...props} componentFactory={props.componentFactory || context} />;
}

WithComponentFactory.displayName = `withComponentFactory(${Component.displayName ||
Component.name ||
'Anonymous'})`;

return WithComponentFactory;
}

0 comments on commit fa5e259

Please sign in to comment.