Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the factory pattern with React

Tags:

reactjs

Let's say I have a really dumb component A. I don't want any of the rendering logic from data to go in this component. Just take some raw data and display it.

Which is the more react way of going about this?

  1. Creating just a bog standard factory function, that given different flags will create a new component with different props set
  2. Making a wrapping component which does all the logic and sets the correct props from the data.

My fear with creating a wrapper is it is just more bloat in the chain of components. When this feels more a tangent.

like image 533
jshthornton Avatar asked Mar 06 '16 14:03

jshthornton


People also ask

What is factory in React?

Instead of creating many if statements we create a function that will dynamically create our components based on the payload. This function is called the factory function. And our App now looks like this. In brief, using a factory function to dynamically create components is factory pattern.

Which design pattern is used in React?

The higher-order component, or HOC pattern, is an advanced React pattern used for reusing component logic across our application. The HOC pattern is useful for cross-cutting concerns — features that require sharing of component logic across our application.

Should you use factory pattern?

Advantage of Factory Design Pattern Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.


1 Answers

Actually separating logic from presentation is pretty usual in React and considered best practise. So solution 2 is the way to go.

Your component A would then probably be a stateless function http://facebook.github.io/react/docs/reusable-components.html#stateless-functions whereas it's father would have only logic methods.

For your information, such a scheme is also the default way of using redux store, see http://redux.js.org/docs/basics/UsageWithReact.html#presentational-and-container-components

like image 59
Mijamo Avatar answered Oct 21 '22 03:10

Mijamo