HBP-Spark
HBP-Spark is a React components library built on top of MobX and React-Bootstrap.
Its goal is to provide a set of useful react components that let you build a consistent user interface with very little boilerplate code. The main focus of the framework is to provide a simple but powerful entry forms management for React applications.
Installation:
npm i -s hbp-spark
Peer dependencies
In order to use hbp-spark in an application, the following peer dependencies need to be installed:
- mobx >=4.0
- mobx-react >=5.0
- react >=15.4.0
- react-dom" >=15.4.0
- react-bootstrap >=0.32
Getting started
HBP-Spark form mechanism is based on a declarative configuration of the form structure as a Javascript (or JSON) Object, like so:
{ fields:{ username: { type: "InputText", label: "Your username" }, age: { type: "InputText", label: "Your age", inputType: "number" }, preferedColor: { type: "InputText", label: "Your prefered color", inputType: "color", value: "#FF0000" } }}
Once this object matching your form data structure this object is provided to a FormStore
instance provided by this library, you can use this store object and provide it to the <Form/>
component. HBP-Spark lets you decide how you want to layout your form, or you can use one of the provided automatic layout (feature coming soon...). Check the example below:
import React from "react"; import { observer } from "mobx-react";import { Row, Grid, Col } from "react-bootstrap";import { Form, FormStore, Field } from "hbp-spark"; let peopleFormStructure = {...}; //See example definition above @observerexport default class PeopleForm extends React.Component { constructor(props) { super(props); this.formStore = new FormStore(peopleFormStructure); } render() { return ( <Form store={this.formStore}> <Grid> <h2>People Form</h2> <Row> <Col xs={4}> <Field name="username" /> </Col> <Col xs={4}> <Field name="preferedColor" /> </Col> <Col xs={4}> <Field name="age" /> </Col> </Row> <h2>Result</h2> <Row> <Col xs={12}> <pre>{JSON.stringify(this.formStore.getValues(), null, 4)}</pre> </Col> </Row> </Grid> </Form> ); }}
Getting the form data
At any time (e.g. when submitting the form), the getValues()
method of the FormStore object returns the processed field values in a structured object matching the definition.
Documentation
To get a more detailed documentation with plenty of examples open a console in the package root and run:
npm install
Then change your current directory to ./docs/
and run :
npm install
npm run start
API Documentation
You can also find the API documentation below:
Table of Contents
- Stores
- Form
- FormFields
- SingleField
- ActionIcon
- GenericList
Stores
Define stores namespace.
FormStore
Mobx store to manage the Form React Component
Parameters
structure
json the underlying form definition
getValues
Get the form field values
Parameters
fields
applyMapping
(optional, defaulttrue
)
Returns object a structured object of the form field values
injectValues
Inject values into form fields, must be input the same format as values
method output
Parameters
values
object structured object of the form field valuesmerge
boolean whether or not to reset the whole form or merge with the passed in values (optional, defaultfalse
)fields
path
string base path for change
reset
Parameters
fields
basePath
string optional, base path to reset from Resets the form to their default values from the base path or completely if no path is provided
update
updates the underlying field definition
Parameters
parentPath
returns the parent path for a field
Parameters
field
(string | field) can be either be a field path or a field object
genSiblingPath
Parameters
validate
validates all form fields at once
registerCustomValidationFunction
registers a custom validation functions that can be used in all fields
Parameters
name
string a name to uniquely identify the rulefunc
function The definition of the validation function. The function parameters are the field value and attribute name. Can be a sync or async function. Expected return value either boolean or promise, indication if validation was successful.errorMessage
string The error message in case the validation fails
registerAxiosInstance
registers a custom axios instance - useful for APIs requiring tokens
Parameters
axiosInstance
object a valid axios instance
toggleReadMode
toggles or force readMode to display form values as pure text instead of input fields
Parameters
status
boolean optional, a boolean indicating what the readMode state should be. If none is passed then the state is toggled
ClipboardStore
A Store handling a virtual clipboard of text selected inside the current browser window. Importing this module will always return the same instance of that store
reset
Clear the value stored in the virtual clipboard
Form
Form component that wraps the underlying Fields
Properties
store
object required - An instance of the FormStore class
values
Get the form field values
Returns object a structured object of the form field values
FormFields
Field is a generic react component that supports all kinds of different input types
Properties
name
string required - Name of the field as defined in the definition object passed to the FormStoreonChange
function Event handler triggered when changes occur to the underlying field value
InputTextField
A simple text input
Options
Parameters
label
string "" - The field labeltype
string "InputText"value
string "" - The current value of the fielddefaultValue
string "" - The defaultValue of the fieldinputType
string "text" - The input type of the field (e.g. text, password, email)placeholder
string "" - A placeholder that is displayed when the field is emptypath
string "" - Field pathuseVirtualClipboard
boolean false - Flag if virtual clipboard feature is enabled for this fieldemptyToNull
boolean true - Flag that determines if empty values are transformed to null in the value function of the formStoredisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form inputvalidationRules
array [] - A list of validation rulescustomErrorMessages
object {} - Definition for custom error messages in the form: {rule: errorMessage}validationOptions
object {onBlur: true, onChange: false} - Validation options to define when validation is executed
InputTextMultipleField
Allows the input of multiple values
Options
Parameters
label
string "" - The field labeltype
string "InputTextMultiple"value
array [] - The current value of the fielddefaultValue
array [] - The defaultValue of the fieldpath
string "" - Field pathmax
number Infinity - Maximum values that the field can haveuseVirtualClipboard
boolean false - Flag if virtual clipboard feature is enabled for this fieldemptyToNull
boolean false - Flag that determines if empty values are transformed to null in the value function of the formStoredisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
TextAreaField
Textarea input field. Field options are the same as for the InputTextField
Options
Parameters
label
string "" - The field labeltype
string "InputText"value
string "" - The current value of the fielddefaultValue
string "" - The defaultValue of the fieldpath
string "" - Field pathemptyToNull
boolean true - Flag that determines if empty values are transformed to null in the value function of the formStoredisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form inputautosize
boolean true - If true, the textarea resizes automaticallyrows
number 1 - How many rows are displayed by default. Represents the min valuemaxRows
number null - How many rows are displayed at most before the field does not grow anymore (only possible if autosize is enabled)resizable
boolean false - If true, the textarea is horizontally resizable by the user
NestedField
Allows the implementation of a nested field structure
NestedRemoveButton
Action button to remove a nested instance, has to be called by the app with <Field.Remove/> component
NestedMoveUpButton
Action button to move up a nested instance in the list, has to be called by the app with <Field.MoveUp/> component
NestedMoveDownButton
Action button to move down a nested instance in the list, has to be called by the app with <Field.MoveDown/> component
NestedDuplicateButton
Action button to duplicate a nested instance in the list, has to be called by the app with <Field.Duplicate/> component
Options
Parameters
label
string "" - The field labelbuttonLabel
string "Add an item" - The label used for adding an item to the repeatable fieldstype
string "Nested"min
number 1 - min of nested children the field can havemax
number 1 - max of nested children the field can havefields
object {} - The nested fields definitionsvalue
string [] - The value of the fielddefaultValue
array [] - The defaultValue of the fieldpath
string "" - Field pathtopAddButton
string true - Whether or not to display the Add button before the fieldsbottomAddButton
string true - Whether or not to display the Add button after the fieldsemptyToNull
boolean false - Flag that determines if empty values are transformed to null in the value function of the formStoredisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
addInstance
add a new instance to a nested field
duplicateInstance
duplicates a nested instance at a given index
Parameters
index
integer the instance to duplicate index
moveInstance
move a nested instance at a given index to a new given index
Parameters
index
integer the instance to movenewIndex
integer the index that instance will have
removeInstance
removes a nested instance at a given index
Parameters
index
integer the instance to remove index
SelectField
A simple select input field
Options
Parameters
label
string "" - The field labeltype
string "Select"value
string "" - The current value of the fielddefaultValue
string "" - The defaultValue of the fieldoptions
array [] - an array of strings or objects with value and label defined by the mappingoptionsUrl
string null - url to fetch the select options fromcacheOptionsUrl
string false - whether to cache optionsUrl fetching responsepath
string "" - Field pathmappingValue
(string | array) "value" - The name(s) of the option object field(s) related to the option value, used to match passed in values to actual optionsmappingLabel
string "label" - the name of the option object field related to the option labeldefaultLabel
string "null" - The label to be displayed as a default value when setemptyToNull
boolean true - Flag that determines if empty values are transformed to null in the value function of the formStoredisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
DropdownSelectField
Form component allowing to select multiple values from a drop-down list with an option to allow custom values entered by the user. The handling of the a custom value is delegated to the application level through the call of the "onAddCustomValue" callback passed in paramter
Options
Parameters
label
string "" - The field labeltype
string "DropdownSelect"value
array [] - The current value of the fielddefaultValue
array [] - The defaultValue of the fieldoptions
array [] - The options of the dropdown, must be an array of objectsoptionsUrl
string null - url to fetch the select options fromcacheOptionsUrl
string false - whether to cache optionsUrl fetching responsepath
string "" - Field pathallowCustomValues
boolean false - if the field should try to accept user inputed valuesmappingValue
(string | array) "value" - The name(s) of the option object field(s) related to the option value, used to match passed in values to actual optionsmappingLabel
string "label" - the name of the option object field related to the option labelmappingReturn
string null - the property of the option object used to return the value(s) - null will return the whole objectreturnSingle
boolean boolean - wether or not to return the first value or an array of valuesmax
number Infinity - Maximum values that the field can haveemptyToNull
boolean false - Flag that determines if empty values are transformed to null in the value function of the formStorelistPosition
boolean "bottom" - Can be "top" or "bottom", whether to display the dropdown list above or below the fielddisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
TreeSelectField
Form component allowing to select multiple values from a tree structure
Options
Parameters
label
string "" - The field labeltype
string "TreeSelect"value
array [] - The current value of the fielddefaultValue
array [] - The defaultValue of the fielddata
array {} - The tree structure to select from, must be an object with eventually an array of childrendataUrl
array null - url to fetch the tree structure fromcacheDataUrl
string false - whether to cache dataUrl fetching responsepath
string "" - Field pathmappingValue
(string | array) "value" - The name(s) of the node object field(s) related to the node value, used to match passed in values to actual tree nodesmappingLabel
string "label" - the name of the node object field related to the node labelmappingChildren
string "children" - the name of the node object field related to the node childrenmappingReturn
string null - the property of the option object used to return the value(s) - null will return the whole objectreturnSingle
boolean boolean - wether or not to return the first value or an array of valuesmax
number Infinity - Maximum values that the field can haveselectOnlyLeaf
boolean false - If enabled, only leaves can be selected and not the intermediary nodesexpandToSelectedNodes
boolean false - If enabled, tree selection modal will recursively expand to all the already selected valuesdefaultExpanded
array [] - an array of arrays describing a path of nodes expanded by default (tested on node labels, path parts are considered as RegExp)showOnlySearchedNodes
boolean false - Flag that determines if nodes that doesn't match the text search should be hiddenemptyToNull
boolean false - Flag that determines if empty values are transformed to null in the value function of the formStoredisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
CheckBoxField
A simple checkbox
Options
Parameters
label
string "" - The field labeltype
string "CheckBox"value
string false - The current value of the fielddefaultValue
string false - The defaultValue of the fieldpath
string "" - Field pathdisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
GroupSelectField
Form component allowing to select on/multiple values from a group of checkboxes/radioboxes
Options
Parameters
label
string "" - The field labeltype
string "GroupSelect"value
array [] - The current value of the fielddefaultValue
array [] - The defaultValue of the fieldoptions
array [] - The options of the dropdown, must be an array of objectsoptionsUrl
string null - url to fetch the select options fromcacheOptionsUrl
string false - whether to cache optionsUrl fetching responsepath
string "" - Field pathmappingValue
(string | array) "value" - The name(s) of the option object field(s) related to the option value, used to match passed in values to actual optionsmappingLabel
string "label" - the name of the option object field related to the option labelmappingReturn
string null - the property of the option object used to return the value(s) - null will return the whole objectreturnSingle
boolean boolean - wether or not to return the first value or an array of valuesmax
number Infinity - Maximum values that the field can haveemptyToNull
boolean false - Flag that determines if empty values are transformed to null in the value function of the formStoredisplayInline
boolean false - Display choices in line, default is display as a listdisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form input
Slider
Slider input field
Options
Parameters
label
string "" - The field labeltype
string "Slider"value
(number | Range) null - The current value. If only a number is provided, a single slider will get rendered. If a range object {min:x, max:y} is provided, two sliders will get rendered.defaultValue
(number | Range) null - The defaultValue of the fieldpath
string "" - Field pathdisabled
boolean false - Is the field disabled or not, a disabled field won't be editable or processed by FormStore.getValues()readOnly
boolean false - Is the field readOnly or not, a readOnly field won't be editable but will be processed by FormStore.getValues()readMode
boolean false - If true, displays the field as label and value without the actual form inputmin
number null (required) - minimum value. You cannot drag your slider under this value.max
number null (required) - maximum value. You cannot drag your slider beyond this value.step
number 1 - The default increment/decrement is 1. You can change that by setting a different number to this property.
SingleField
SingleField is a generic react component that supports all kinds of different input types without a form component
ActionIcon
ActionIcon component
Properties
icon
string required - glyphicon to display https://getbootstrap.com/docs/3.3/components/#glyphiconsonClick
function optional - callback for when action is clicked
GenericList
Generic List component that renders a list of items using Bootstrap Panels
Properties
items
array required - an array of items to be displayed in the list. Can be an array of primitives or objectsexpanded
boolean optional - if the panel is expanded by defaultitemTitle
object optional - react component to render the title for individual items. Gets passed the item to be rendered as a prop. Default value: ({ item }) => itemitemBody
boolean optional - react component to render the body for individual items. Gets passed the item to be rendered as a prop. Only necessary if you want a body to be displayedactions
array required - an array of actions. An actions can be any react components that get rendered in the top right corner of the panel. For callback, implement the onClick which gets called with the selected item.