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.
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:
I see article based on classes but this is too much code, do you have a solution?
what kind of solution are you looking for ?
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.
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?
Good question. This is another blog worthy topic. I'll address it in the next post 😉
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.
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