Reputation: 392
I'm having a mental block right now, I have a HOC component that's checking for a feature flag like below:
const withEnabledFeatures = (WrappedComponent: any) => {
class WithEnabledFeatures extends React.Component<any> {
enabledFeatures = (): Array<string> => {
if (window === undefined) return [];
return window.AH.featureFlags;
}
isFeatureEnabled = (feature: string): boolean => {
return this.enabledFeatures.includes(feature);
}
render() {
return (
<WrappedComponent
enabledFeatures={this.enabledFeatures()}
isFeatureEnabled={this.isFeatureEnabled}
{...this.props}
/>
)
}
}
};
export default withEnabledFeatures;
And I will use this as a prop in another component say
isFeatureEnabled('feature_a');
Which will return true if it exists or false if not.
My question is my isFeatureEnabled
function correct?
Upvotes: 0
Views: 111
Reputation: 813
Added return inside HOC
for WithEnabledFeatures
as well as corrected the isFeatureEnabled
return statement
const withEnabledFeatures = (WrappedComponent: any) => {
return class WithEnabledFeatures extends React.Component<any> {
enabledFeatures = (): Array<string> => {
if (window === undefined) return [];
return window.AH.featureFlags;
}
isFeatureEnabled = (feature: string): boolean => {
return this.enabledFeatures().includes(feature);
}
render() {
return (
<WrappedComponent
enabledFeatures={this.enabledFeatures()}
isFeatureEnabled={this.isFeatureEnabled}
{...this.props}
/>
)
}
}
};
export default withEnabledFeatures;
Upvotes: 0
Reputation: 8947
No, you are not calling this.enabledFeatures
as a method, you are trying to access a member on it. Use this.enabledFeatures().
Also, the HOC factory method is not returning the extended class.
const withEnabledFeatures = (WrappedComponent: any) => {
return class WithEnabledFeatures extends React.Component<any> {
enabledFeatures = (): Array<string> =>
(window === void 0) ? [] : window.AH.featureFlags;
isFeatureEnabled = (feature: string): boolean =>
this.enabledFeatures().includes(feature); // <-- Here, ()
render() {
return (
<WrappedComponent
enabledFeatures={this.enabledFeatures()}
isFeatureEnabled={this.isFeatureEnabled}
{...this.props}
/>
)
}
}
};
export default withEnabledFeatures;
(I also optionally compressed your code and added a best practice, void 0
)
Upvotes: 1