dripto
dripto

Reputation: 619

React - reuse patterns for almost similar components

I have a react site which contains a number of almost similar pages (displaying forms to the user). For example,

  1. Page x contains a form with fields a, b & c.
  2. Page y contains a form with fields b, c & d.
  3. Page z contains a form with fields a, c & d.

These pages (& the forms) might have minor CSS differences also (depending on the number of fields etc). All of these forms have client validation.

I can develop this in react by

  1. creating a component with fields a, b, c & d together and only conditionally render fields, validation logic etc depending on the page type.
  2. creating separate components for each of the pages.

I'm quite new to react so couldn't decide on which one is the right react way or pattern of doing this. kindly help.

Upvotes: 3

Views: 619

Answers (2)

Rajesh
Rajesh

Reputation: 24955

In my opinion, its always better to have a list of dumb components and an HOC that bring them together and directs the flow.

You can have a huge component with tons of conditional branching. But this will be complex to understand and maintain. Having separate allows you to have better control of logic and also reduces dependency/ cross impact.


You have a financial based product, like a bank application.

You have following pages/ use-cases:

  1. Online transaction.
  2. View balance/ statement
  3. KYC form update
  4. Personal banker communication.

Either page you go to, you will need user to login and so login form is common. However, point 3 & 4 are not that critical. So just customer id and password would suffice.

For point 1 & 2, having a more secure approach is required. So you may add phone/email verification. So essentially you can have a same login page but let HOC decide the flow.

Upvotes: 2

Nikola Diklich
Nikola Diklich

Reputation: 516

The thing in React is that there is only a few scenarios where there's only one right way to render something. This is primarily opinion-based. I would personally go with option 1, and tweak the components so that they are shown properly on the page. But who knows, maybe you run into a brick wall, and have to settle for the option 2. You can never know until you try. To summarize: do whatever feels more natural to you, and try not to duplicate your code.

Upvotes: 0

Related Questions