DEV Community

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

Collapse
 
ryskin profile image
Alexey

I see article based on classes but this is too much code, do you have a solution?

Collapse
 
shadid12 profile image
Shadid Haque

what kind of solution are you looking for ?

Thread Thread
 
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.

Collapse
 
ashkanmohammadi profile image
Amohammadi2

The only other solution that I can think of, is to use an object which has component types as keys and the actual components as values.

Then you can map your component type to the object keys to instantiate different types of components

To add a new type, you'll just need to add another key & value pair to the object