首页 > 解决方案 > What is the best way to reuse form components in React?

问题描述

I have around 20 forms in my app where most of them includes similar input fields. A single form would look like this.

<form>
  <div>
    <input name="first_name" />
    <error />
  </div>
  <div>
    <input name="last_name" />
    <error />
  </div>
  <div>
    <input name="phone" />
    <error />
  </div>
  <div>
    <input name="address" />
    <error />
  </div>
</form>

first_name, last_name fields can be categorized as a common input group that will on most forms. phone and address group also can be found in many forms. Like-wise there are input groups that are common.

I'm trying to re-use the common ones. And found two ways.

  1. Wrap common fields into components

This will be something like this

<form>
  <SectionOne />
  ...
</form>

const SectionOne = () => {
  return (
    <>
      <div>
        <input name="first_name" />
        <error />
      </div>
      <div>
        <input name="last_name" />
        <error />
      </div>
    </>
  )
}
  1. Wrap input and error

This will be something like this

<form>
  <Input 
    ....
  />
  <Input 
    ....
  />
  ...
</form>

const Input = () => {
  return (
    <div>
      <input name="first_name" />
      <error />
    </div>
  )
}

I would like to know which will be the best practice when building reusable app in the long run without duplication.

If I'm missing any other best practice I would like to know.

input means text boxes, selects, radio buttons etc.

标签: reactjsformsreusabilitycode-duplication

解决方案


创建纯组件

const Input = inputs => inputs.map(input => ( <><input name={input} /> <error/></>))

在某处重用它

<Input inputs={['first_name', 'last_name']} />

推荐阅读