Skip to content

Instantly share code, notes, and snippets.

@felquis
Last active November 19, 2019 17:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felquis/9e4d06d4be16e0f8e01ed21b2180f743 to your computer and use it in GitHub Desktop.
Save felquis/9e4d06d4be16e0f8e01ed21b2180f743 to your computer and use it in GitHub Desktop.
How do I create forms with React with no other lib/package/module

In this gist I describe how I use arrays to create web forms with JavaScript React, the same pattern can be use with any JS lib or, vanilla js.

First, what kind of form are we talking about? §I applied this method in forms up to twelve inputs, including type text, email, select, select multiple, date rage, number range, checkbox.

In a gist, create an array and each array indice is an object that describes how a form input of any given type should render. I put this array in my state and on each input on change I map my fields array and update it's value, onChange I can also call async validation functions that will map and update the fields array with the current input validity.

For me it was the simpliest way to build any given form and still have a fine control over how everything is rendered.

This, would be a select input, with all it's props.

[{
  name: 'status',
  type: 'select',
  label: 'Status',
  value: 'active',
  options: [{
    label: 'Select one',
    value: '',
  }, {
    label: 'Active',
    value: 'active',
  }, {
    label: 'Inactive',
    value: 'inactive',
  }]
}]

Once you describe your inputs in an array, use map to render each input.

const MyForm = ({ fields, onChange, onSubmit }) => (
  <form onSubmit={onSubmit}>
    {fields.map(field => {
      // here you check the field.type and render the proper JSX.
    })}
  <form>
)

The on change event now should map the fields, and rewrite the object with the new field value based in the name prop.

onChange = (event) => {
  this.setState(() => {
    fields: this.state.fields.map(field => {
      // if the field.type is a special one, for example an array of values,
      // §you should put more conditionals to the map function bellow
      if (field.name === event.target.name) {
        return {
          ...field,
          value: event.target.value,
        }     
      }

      return field
    })
  })
}

That is it, how are you building forms lately?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment