P
P
Persotr272022-02-06 20:46:23
React
Persotr27, 2022-02-06 20:46:23

How to make a React component that is diverse in terms of data but with common functionality?

Hello. I have a react component - a form. A form can have different types of fields and their number. For example, one form can have 2 input text, 3 button radios, the second one can have no input text at all, but have a file receiver, the third one consists of checkboxes. And there are 12 such different types of forms, for example. An important feature is that they all have several common required fields. Their interface should be visually the same, and there is also some common functionality. On submitting the form, regardless of its type, I want to do something with the data (which can be different), process them in the same way.

How to organize such a component? The simplest option, through a lot of switch cases, will eliminate the need to create a separate flow and component for each type of form, and duplicating the code of the general functionality, but nevertheless, such a component can be redundant.

I hope the question is clear. What do you advise?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
@
@insighter, 2022-02-06
_

If you have experience in developing gui applications on the desktop, then it is better not to drag these approaches into React. Here, code reuse is possible (one does not exclude the other):
1. Through hooks
2. Through decorating components
For example, there is a certain action bar with buttons "record", "cancel" and I want to inherit from it and add a "help" button.

function ActionBar({children}){
return(<div>
  <button>Cancel<button/>
  <button>Save<button/>
  {children}  // -- здесь будут размещены "дочерние" компоненты
</div>)
}

Usage example
function ActionBarWithHelp(){
return(
  <ActionBar>
    <button>Help<button/>
  </ActionBar>
</div>)
}

Y
y0u, 2022-02-06
@y0u

Read about Compound components , Hooks and React Context . In the end, you will be able to collect approximately what you have in mind.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question