DEV Community

Discussion on: React.js with Factory Pattern ? Building Complex UI With Ease

 
click2install profile image
click2install

A strategy pattern would adhere to OCP. You can define you strategies externally and pass them in. Similarly a more correct factory where you can register a key and value allows for no changes to implementation when adding more items.

Thread Thread
 
johannes5 profile image
Johannes5

Could you provide an example of a strategy pattern with react components?

And how would you feed components with different props, when you have a js Map or Object?

Thread Thread
 
shadid12 profile image
Shadid Haque

Good question. This is another blog worthy topic. I'll address it in the next post 😉

Thread Thread
 
johannes5 profile image
Johannes5 • Edited

That's great!

In my case, I used the factory pattern with a component called ItemFactory .
Which makes one of a lot of possible requests using React Query. I have the different request functions dynamically selected inside another module and used inside a single:

useQuery(["itemFactory", sourceCategory, ...args], fetchItemsFromTheCorrectEndpointBasedOn (sourceCategory, ...args))

The sourceCategory also decides (via if-statement) what type of ItemComponent {... withWhatSelectionOfProps} is being rendered.