@guidesmiths/react-form-builder
npm i @guidesmiths/react-form-builder

@guidesmiths/react-form-builder

React Form Builder

by guidesmiths

1.1.38 (see all)License:MITTypeScript:Not Found
npm i @guidesmiths/react-form-builder
Readme

react-form-builder

React form builder using json schema

NPM JavaScript Style Guide

All Contributors

Install

npm install --save @guidesmiths/react-form-builder

Usage

import React, { useEffect, useState } from 'react'
import forms from './forms.json'
import FormBuilder from 'react-form-builder'

const onSubmitForm = (data) => {
    !isLoading &&
      alert(
        `You have submitted your form correctly Data: ${'\n'} ${JSON.stringify(
          data,
          null,
          2
        )}`
      )
    setLoading(true)
    setTimeout(() => {
      setLoading(false)
    }, 1000)
  }

const Example = () => {
  render() {
   <FormBuilder
        idForm={forms.contact.id}
        form={forms.contact}
        onSubmit={onSubmitForm}
        isoCode='ES'
        onLinkOpen={onLinkOpen}
        isLoading={isLoading}
      />
  }
}

Live Playground

For examples of react-form-builder in action go to:

http://guidesmiths-react-form-builder.s3-website.eu-central-1.amazonaws.com/

Formbuilder options

OptionDescriptionTypeDefault
idForm*Id for the formstring''
form*The json with the questions to createjson-
onSubmit*Action to be realised "onSubmit" formfunction-
languageShortcut with the language to render components in multiple languages (country,date)

Available laguages: es,de,fr,en
stringen
isoCodeIsocode of the country to show as default in phone inputstringGB
isMobileA boolean toggle is assigned to check if we are from a mobile port viewbooleanfalse
countryAndRegionsDataArray of objects with the acronym(s) and the names of the countries that you want to display in the countrySelect (see example)Array of objects-
onLinkOpenfunction to be executed when there is a custom linkfunction-
CountryAndRegionsData example:
[
  { "cn": "MyOwnCountry1", "cs": "MC1" },
  { "cn": "MyOwnCountry2", "cs": "MC2" },
  { "cn": "MyOwnCountry3", "cs": "MC3" },
  { "cn": "MyOwnCountry4", "cs": "MC4" }
]

Questions

Checkbox

OptionDescriptionTypeDefault
name*Checkbox namestring-
type*Must be checkboxstring-
labelText shown next to the checkbox. This text can be written in markdown stylestring''
isFullWidthDefine if the field takes all the available width in the grid or notbooleanfalse
defaultCheckedChecked component by defaultbooleanfalse
errorMessagesjson
requiredError message to display on submit if the checkbox is not checked and is requiredstring''
registerConfigjson
requiredDefine if the checkbox is requiredbooleanfalse

Reminder: A custom link it will be indicated by the start of a '#' in the markdown label. This link will execute the action that you had sent in the onLinkOpen param in the ReactFormBuilder component.

Checkbox example

    {
          "name": "terms_and_conditions",
          "label": "This is the label of the checkbox with a [customLink](#customLink) and [normalLink](https://www.dcsl.com/careers/)",
          "type": "checkbox",
          "defaultChecked": false,
          "errorMessages": {
            "required": "This field is required"
          },
          "registerConfig": {
            "required": true
          }
        }

https://user-images.githubusercontent.com/79102959/134894112-e4f38ced-0992-428c-95c3-bcdce20cd858.mp4

Country

OptionDescriptionTypeDefault
name*Country component namestring-
type*Must be countrystring-
labelText shown over the coutnry liststring''
languageAn string with the language shortcode in which you want to display the country names opt:
Available laguages: es,de,fr,en
stringen
placeholderPlaceholder displayed in the selectstring''
priorityOptionsArray of strings with shortcode(s) of the countries that want to be displayed first in the countries list. Ex: ['GB', 'ES']string''
returnCountryNameReturns the country name (in English) as each option value, instead of the country codebooleanfalse
countryAndRegionsDataAn object or array of objects with the acronym(s) and the names of the countries that you want to be shown in the select.json[]
countryNameThe name of the countrystring''
countryShortCodeTo display the short code(s) for the countries Ex: ['GB', 'ES']string''
errorMessagesjson
requiredError message to display on submit if there is no country selectedstring''
registerConfigjson
requiredDefine if the country select is requiredbooleanfalse

Reminder: the 'countryAndRegions' prop that can be sent in the ReactFormBuilder will be rendered in this component and will replace the default list.

Country example:

{
  "name": "country_of_residence",
  "type": "country",
  "label": "This is the label of the country select",
  "placeholder": "Please select an option ^^",
  "priorityOptions": ["GB", "ES"],
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  }
}

Custom list country example:

{
  {
      countryName: 'MyOwnCountry1',
      countryShortCode: 'MC1'
    },
    {
      countryName: 'MyOwnCountry2',
      countryShortCode: 'MC2'
    },
    {
      countryName: 'MyOwnCountry3',
      countryShortCode: 'MC3'
    },
    {
      countryName: 'MyOwnCountry4',
      countryShortCode: 'MC4'
    }
}

{
  "name": "country_of_residence",
  "type": "country",
  "label": "This is the label of the country select",
  "placeholder": "Please select an option ^^",
  "priorityOptions": ["GB", "ES"],
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  }
}

https://user-images.githubusercontent.com/79102959/134897712-95e4391c-cfbb-42cd-b813-06596d9b7096.mov

Date

OptionDescriptionTypeDefault
name*Date name componentstring-
type*Must be datestring-
labelText shown over the date inputstring''
placeholderText to be displayed as placeholder in the date inputstring''
minAgeMinimun age that user should have to make the submitint''
dateFormatFormat to be applied in the date inputstringdd/MM/yyyy
openToDateDate in which the calendar will be opened. If this attribute is empty and we have a minAge attribute, the calendar will be opened -- minAge years ago since today to improve make it easier for the user. If we dont use this attribute the calendar will be opened in todays datestringdd/MM/yyyy
errorMessagesjson
requiredError message to display on submit if the date hasn't be selected and is requiredstring''
underAgeError message to display on submit if it is chosen a date that represents a user younger than the minAge attributestring''
registerConfigjson
requiredDefine if the date is required or notbooleanfalse

Date examples

Basic date example

{
  "name": "dob",
  "type": "date",
  "label": "Date of birth",
  "placeholder": "dd/mm/yyyy",
  "openToDate": "1/1/2000",
  "errorMessages": {
    "required": "This field is required",
  },
  "registerConfig": {
    "required": true
  }
}

Under age date example

{
  "name": "dob",
  "type": "date",
  "label": "Date of birth",
  "placeholder": "dd/mm/yyyy",
  "minAge": 18,
  "errorMessages": {
    "required": "This field is required",
    "underAge": "You must be 18 years old or above"
  },
  "registerConfig": {
    "required": true
  }
}

https://user-images.githubusercontent.com/79102959/134897303-817957ba-12d1-4c0c-a64f-6ab0c99d72fd.mp4

Input

OptionDescriptionTypeDefault
name*Input namestring-
type*Must be inputstring-
labelText shown with the inputstring''
placeholderPlaceholder text to be displayedstring''
iconjson
nameName of the icon that we want to be displayed Opt: ['question-circle']string-
fillIcon colorstringblack
tooltipjson
textText to be displayed on icon hoverstring''
configinside this json we could define any typical theme UI property to style the tooltipjson
errorMessagesjson
requiredError message to display on submit if the checkbox is not checked and is requiredstring''
patternError message to display if there is an error pattern in the input textbooleanfalse
registerConfigjson
requiredDefine if the checkbox is requiredbooleanfalse
patternDefine the pattern to check the inputstring""

Input examples

Basic input example

{
  "name": "email",
  "type": "input",
  "label": "",
  "placeholder": "Email Address*",
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  }
}

Input with pattern control example

{
  "name": "email",
  "type": "input",
  "label": "",
  "placeholder": "Email Address*",
  "errorMessages": {
    "required": "This field is required",
    "pattern": "Invalid email"
  },
  "registerConfig": {
    "required": true,
    "pattern": "/^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$/"
  }
}

Input with styled icon

{
  name: 'inputName',
  type: 'input',
  label: 'input label',
  placeholder: 'input placeholder',
  icon: {
    name: 'question-circle',
    fill: 'red'
  },
  tooltip: {
    text: 'tooltip text example',
    config: {
      backgroundColor: 'green'
    }
  },
  errorMessages: {
    required: 'This field is required',
    pattern: 'This is not the right pattern'
  },
  registerConfig: {
    required: true
  }
}

https://user-images.githubusercontent.com/79102959/134945983-c0c38274-05c7-42b7-8ad3-c80b33db6611.mov

Markdown

OptionDescriptionTypeDefault
name*markdown component namestring-
type*must be markdownstring-
labelText to be displayed, it will be formatted with markdown stylestring''

Markdown examples

Markdown example

{
    name: "Markdown component",
    type: "markdown",
    label: "El texto a **mostar** en el markdown [exmaple]()"
}

Markdown

MultipleCheckbox

OptionDescriptionTypeDefault
name*MultipleCheckBox namestring-
type*must be multiple_checkboxesstring-
labelText to show like the question textstring''
configjson
optionsjson
optionsIt contains all the options to be rendered in the multicheckbox componentObject Array-
label or srcThe label displayed with the option (can use markdown format) or the src of the image to be renderedstring''
valueThe value of the optionstring''
errorMessagesjson
requiredError message to display on submit if the multiplecheckbox is not checked and is requiredstring''
minimumLenText to be displayed in case not minimunLen items has been selectedstring''
maximumLenText to be displayed in case that more than maximumLen items has been selectedstring''
registerConfigjson
minimumLenMinimum number of options that user must selectint0
maximumLenMaximum number of options that user can selectint-
requiredDefine if the multiplecheckbox is requiredbooleanfalse

Multiplecheckbox examples

Basic multiplecheckbox

{
  "name": "multiplecheckbox_name",
  "type": "multiple_checkboxes",
  "placeholder": "Please select all that apply",
  "label": "What option do you prefer?",
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  },

  "config": {
    "options": [
      {
        "value": "option1",
        "label": "LabelOption1"
      },
      {
        "value": "option2",
        "label": "LabelOption2"
      },
      {
        "value": "option3",
        "label": "LabelOption3"
      }
    ]
  }
}

Multiplecheckbox with images and labels

{
  "name": "multiplecheckbox_name",
  "type": "multiple_checkboxes",
  "placeholder": "Please select all that apply",
  "label": "What option do you prefer?",
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  },

  "config": {
    "options": [
      {
        "value": "option1",
        "src": "/src/assets/image1"
      },
      {
        "value": "option2",
        "label": "LabelOption2"
      },
      {
        "value": "option3",
        "src": "/src/assets/image3"
      }
    ]
  }
}

Multiplecheckbox with minimumLen

{
  "name": "multiplecheckbox_name",
  "type": "multiple_checkboxes",
  "placeholder": "Please select all that apply",
  "label": "What option do you prefer?",
  "errorMessages": {
    "required": "This field is required",
    "minimumLen": "You must choose at least two options"
  },
  "registerConfig": {
    "minimumLen": 2,
    "required": false
  },
  "config": {
    "options": [
      {
        "value": "option1",
        "label": "LabelOption1"
      },
      {
        "value": "option2",
        "label": "LabelOption2"
      },
      {
        "value": "option3",
        "label": "LabelOption3"
      }
    ]
  }
}

https://user-images.githubusercontent.com/79102959/134945855-52577cab-9b16-4df5-8978-b269be0ffce9.mov

Phone

OptionDescriptionTypeDefault
name*Phone component namestring-
type*must be phonestring-
labelText to show over the inputstring''
placeholderPlaceholder text to be displayed in the selectstring''
defaultCountryCountry to show by defaultstringGB
errorMessagesjson
requiredError message to display on submit if the phone input is not filled and is requiredstring''
registerConfigjson
requiredDefine if the phone input is requiredbooleanfalse

Reminder: The isoCode prop that can be sent in the ReactFormBuilder component will define the default country displayed in the phone field.

Basic phone

{
  "name": "phone",
  "type": "phone",
  "label": "",
  "registerConfig": {
    "required": true
  },
  "placeholder": "Phone",
  "errorMessages": {
    "required": "This field is required"
  }
}

https://user-images.githubusercontent.com/79102959/134948115-4f461d76-8d06-4cb8-adc0-e2bef5f9d16f.mov

RadioButton

OptionDescriptionTypeDefault
name*RadioButton namestring-
type*must be radiostring-
labelText to show like the question text. This text can be written in markdownstring''
optionsObject array that will contain all the options that you want in the radio buttons componentarray
valuethe value of the optionstring-
labelthe label displayed with the optionstring-
errorMessagesjson
requiredError message to display on submit if the checkbox is not checked and is requiredstring''
registerConfigjson
requiredDefine if the radioButton is requiredbooleanfalse

RadioButton example

Basic radiobutton

{
  "name": "radio_name",
  "label": "este es el texto de la pregunta",
  "type": "radio",
  "options": [
    {
      "value": true,
      "label": "YES"
    },
    {
      "value": false,
      "label": "NOP"
    }
  ],
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  }
}

https://user-images.githubusercontent.com/79102959/134948337-03618f4c-6cc7-409a-b95b-c3737ade9130.mov

Select

OptionDescriptionTypeDefault
name*Checkbox namestring-
type*must be selectstring-
labelText shown over the select questionstring''
placeholderPlaceholder text to be displayed in the selectstring''
configjson
optionsjson
optionsIt contains all the options to be rendered in the select componentObject Array-
labelThe label displayed in select optionstring''
valueThe value of the select optionstring''
errorMessagesjson
requiredError message to display on submit if there is no selection and it is requiredstring''
registerConfigjson
requiredDefine if the select is requiredbooleanfalse

Select examples

Select basic example

{
  "name": "color",
  "type": "select",
  "placeholder": "Please choose an option",
  "label": "What is your favorite color?",
  "errorMessages": {
    "required": "This field is required"
  },
  "registerConfig": {
    "required": true
  },
  "config": {
    "options": [
      {
        "value": "red",
        "label": "Red"
      },
      {
        "value": "black",
        "label": "Black"
      },
      {
        "value": "prefer_not_say",
        "label": "prefer not to say"
      }
    ]
  }
}

https://user-images.githubusercontent.com/79102959/134949537-3647437e-0330-4692-bd30-ef6aa319bd7b.mov

Accessibility

The accessibility requirements for all the form tags are already configured in the library. For components (input, checkbox, select, radio…) different attributes have been introduced that can be configured through props.

Next, we can see different attributes and tags to adjust the accessibility of the form and how to configure them:

Attribute/TagDescription
Aria-describedbyTo configure that, it's necessary to pass “name form” as a prop
Fieldset / LegendTags that are being used to group and associate related form controls (you can see in the multiple checkbox example given below)
RequiredTo indicate if the field is necessary to fill or not while completing the form
PlaceholderUsed to guide and help the user to describe the format and expected value for the field
TypeTo specify the type of elements to display
AccessibilityIn radio button needs to pass as a props "accessibility": true
AccessibilityErrorthe main form also needs to have "accessibilityError": true as a props
  • To define the style for the fields, as we use theme-ui, we can either do inline-styling using style=”” or instead sx=”” where you pass the style accordingly. Also, we can include an “id” attribute for input that needs a unique style.

  • For the markdown component, we can add the corresponding tag to the text or title. To illustrate that, if the title is an h2, it will include “##” before text, or, if the title is an h3, it will include “###”, and so on.

Following are the few code examples to see how we use each component:

Main form

{
  "en": {
    "contact": {
      "name": "Contact Form",
      "enabled": true,
      "accessibilityError": true,
      "questions": [...]
    }
  }
}

Input tag

<div class="form-group">
    <label for="first_name">First name*</label>
    <input
        type="text"
        class="form-control"
        placeholder=""
        id="first_name"
        name="first_name"
        aria-describedby="error_message_first_name"
        required>
    <span class="invalid-feedback"
          style="display:block;"
          id="error_message_first_name">This field is required</span>
</div>
<div class="form-group">
    <label for="age">Age Range</label>
    <select class="form-control"
            autocomplete="off"
            id="age"
            name="age"
            aria-describedby="error_message_age"
            required
    >
        <option value="" disabled>Please make a selection</option>
        <option value="one">One</option>
        <option value="two">Two</option>
        <option value="three">Three</option>
    </select>
    <span class="invalid-feedback"
          style="display:block;"
          id="error_message_age">Please make a selection</span>
</div>

Multiple checkbox

<div class="form-group" ref="what_sport_interested_in">
    <fieldset>
        <legend for="what_sport_interested_in">Are you interested in any of the sports below?</legend>
        <span class="invalid-feedback"
          style="display:block;"
          id="error_message_what_sport_interested_in">Please make a selection</span>
        <div class="form-group container">
            <div class="row">
                <div class="form-check col-12 col-md-6">
                    <input type="checkbox" 
                      class="form-check-input"
                      value="Tennis"
                      id="what_sport_interested_in_tennis"
                      name="what_sport_interested_in_tennis"
                      aria-describedby="error_message_what_sport_interested_in">
                    <label class="form-check-label" for="what_sport_interested_in_tennis">Tennis</label>
                </div>
                <div class="form-check col-12 col-md-6">
                    <input type="checkbox" 
                      class="form-check-input"
                      value="Football"
                      id="what_sport_interested_in_football"
                      name="what_sport_interested_in_football"
                      aria-describedby="error_message_what_sport_interested_in">
                    <label class="form-check-label" for="what_sport_interested_in_football">Football</label>
                </div>
            </div>
        </div>
    </fieldset>
</div>

Checkbox fields

<div class="form-group">
    <label for=”privacy_policy">Privacy policy*</label>
    <input
        type="checkbox"
        class="form-control"
        id="privacy_policy"
        name="privacy_policy"
        aria-describedby="error_message_privacy_policy"
        required>
    <span class="invalid-feedback"
          style="display:block;"
          id="error_message_first_name">This field is required</span>
    <div>
         <p> I confirm I am aged 18 years or older, a resident of the United Kingdom and have read and agree to the competition terms and condition and privacy policy</p>
   </div>

To contribute

  1. npm install
  2. npm start
  3. Open another tab and do cd example
  4. npm install
  5. npm start

See localhost:3000

Any change on the root src library will be reflected on the usage in the example folder.

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Pablo Albaladejo

💻 🧑‍🏫

Ismael Bakkali

💻 👀 🐛

Francisco Valdesoiro

💻 📓 🐛

Adrián Rodríguez

💻 📖 ⚠️

Sofía Sánchez

💻 ⚠️

Iván Esteban

💻 🐛

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT © Guidesmiths

Downloads/wk

450

GitHub Stars

13

LAST COMMIT

2mos ago

MAINTAINERS

5

CONTRIBUTORS

18

OPEN ISSUES

13

OPEN PRs

4
VersionTagPublished
1.1.38
latest
4d ago
No alternatives found
No tutorials found
Add a tutorial