Factory Pattern in React Js

|
| By Babita Kapoor

We create a function that will dynamically create our components based on the payload rather than writing numerous if statements. This procedure is called factory function. This is how our app currently appears. In a nutshell, the factory pattern is the use of a factory function to dynamically create components.

Consider that we are creating a dashboard. We receive a user object from our back end when a user logs in. We will decide what our user sees in the dashboard based on that object. Let’s assume that the object returned from our server is user a.
user_a = {
name: "jhon doe",
items: [
{
title: "Card 1",
details: {
// ...more info
},
type: "A"
},
{
title: "Card 2",
details: {
// ...more info
},
type: "B"
},
{
title: "Card 3",
details: {
// ...more info
},
type: "C"
},
{
title: "Card 4",
details: {
// ...more info
},
type: "D"
}
] }

We will render a card component depending on the kind of object. Let’s assume that our users would see this:

React-pattern

Now, that appears to be a fairly simple process. We can write our components as follows and render them in our app component (container component) with a straightforward switch statement because there are four different types of card components.
function A() {
return(

Type A Component

)
}
function B() {
return(

Type B Component

)
}
function C() {
...
}
function D() {
...
}

App.jsx

function App() {
return (

{cards.map(card => {
switch (card.type) {
case "A":
return <A />;
case 'B':
return <B />;
case 'C':
return <C />;
case 'D':
return <D />;
default:
return null;
}
})}

)
}

But as our application gained popularity, we were told to add 10 more distinct card component types. There are now cards A, B, C, D, E, F, G, H, I, J, K, and so on. Of course, at this point, we have the option to keep including if statements or a switch statement. However, it will start to appear messy soon.

Additionally, the Single Responsibility Principle will be broken. What to render based on the payload should not be an issue of the app component. To keep our code organized, we require a layer of abstraction.

Okay, so this is the answer. We develop a function that will dynamically create our components based on the payload rather than writing numerous if statements. This function is called the factory function.

function Factory(props) {
switch (props.component.type) {
case "A":
return <A />;
case "B":
return <B />;
case "C":
return <C />;
default:
return <div>Reload...</div>;
}
}

And now our app appears as shown.

return (
<div>
{cards.map(card => (
<Factory component={card} />
))}
</div>
);

Simply put, the factory pattern is the use of a factory function to build components on demand.

Leave a Reply

Your email address will not be published. Required fields are marked *