Reputation: 29
Have some data in component state, that is mapped over like:
render() {
return (
<div className="App">
{this.state.items.map(item => {
const enhancer = item.color = 'red' ? EnhancerA : EnhancerB
const Enhanced = withEnhancement(enhancer)
return <Enhanced {...item} />
})}
</div>
)
}
withEnhancement
is a HoC
that takes either EnhancerA
or EnhancerB
and returns a new component.
Would this be bad practice according to the React docs over dont use hocs inside the render method or would this be alright, as doing it inside the return statement?
Upvotes: 2
Views: 163
Reputation: 4942
I'd say it's pretty bad, yes... But there's a very simple workaround.
Put this code BEFORE the class declaration:
const EnhancedA = withEnhancement(EnhancerA);
const EnhancedB = withEnhancement(EnhancerB);
and inside your render function, choose which enhanced component to use:
const Component = item.color = 'red' ? EnhancedA : EnhancedB;
return <Component {...item} />;
The point of this being, you're only creating the "enhanced components" once, and reusing them inside of your map
function, instead of creating a new component instance for every new element on your array.
Upvotes: 3
Reputation: 169032
Yes, it would be bad.
For the sake of what's discussed in the React docs you linked, they're the same thing, and this would also cause unnecessary forced rerenders.
Upvotes: 2