Skip to content

Latest commit

 

History

History
2139 lines (1560 loc) · 61.2 KB

docs.md

File metadata and controls

2139 lines (1560 loc) · 61.2 KB

Table of Contents

ColorPicker

A control component for picking a hex color value. Built using the react-color ChromePicker.

Parameters

  • value String? The hex value of the selected color
  • onChange Function? A function called with the new hex value when a color is selected
  • onOpen Function? A function called when the picker is expanded
  • onClose Function? A function called when the picker is closed
  • active Boolean? A boolean that controls whether the picker is expanded or not.

Examples

function BackgroundSetter ({ backgroundColor, setBackgroundColor }) {
  return (
    <div>
      <h1> Set background color </h1>
      <ColorPicker
        value={ backgroundColor }
        onChange={ setBackgroundColor }
      />
    </div>
  )
}

Paginator

A control component for navigating between multiple numbered pages.

Parameters

  • value Number The number of the current page (optional, default 1)
  • onChange Function? A function called with the new value when a page is clicked.
  • min Number The number of the first page (optional, default 1)
  • max Number The number of the last page. (optional, default 1)
  • alwaysShow Boolean Always show the component, even when there's only one page visible. (optional, default false)
  • pagesShown Number The number of pages to display around (and including) the current page (optional, default 3)
  • previousLabel String The text of the "previous page" button (optional, default 'Prev')
  • nextLabel String The text of the "next page" button (optional, default 'Next')
  • delimiter String The delimiter that will be shown when there are hidden pages (optional, default '...')

Examples

function ShowPages ({ pages, currentPage, changeCurrentPage }) {
  return (
    <div>
      <Page
        page={pages[currentPage]}
      />
      <Paginator
        value={currentPage}
        onChange={changeCurrentPage}
        max={pages.length}
      />
    </div>
  )
}

TabBar

A control component for navigating among multiple tabs

Parameters

  • vertical Boolean A boolean setting the className of the ul to 'horizontal' (default), or 'vertical', which determines the alignment of the tabs (optional, default false)
  • options Array An array of tab values (strings or key-value pairs)
  • value (String | Number) The value of the current tab
  • onChange Function? A function called with the new value when a tab is clicked
  • activeClassName String The class of the active tab (optional, default 'active')

Examples

function ShowTabs ({ currentTab, setCurrentTab }) {
  return (
    <div>
      <TabBar
        options={['Tab 1', 'Tab 2']}
        value={currentTab}
        onChange={setCurrentTab}
      />
    </div>
  )
}

Button

A simple button component that can be used independently, or as part of a form.

Conditionally adds classes and/or sets aria-disabled depending on passed props. If the button is disabled or submitting, the onClick handler will be overridden with a noop. This is especially helpful when preventing duplicate form submissions for both mouse and keyboard actions.

In addition to the props below, any extra props will be passed directly to the inner <button> element.

If a className is provided to the component, it will be appended to the conditionally added classes.

Note: Instead of targeting the :disabled pseudo-class or [disabled] attribute, you can target [aria-disabled=true] to apply similar styling. Using the ARIA attribute keeps the <button> in the taborder and will be read as "disabled" or "dimmed" by screen reader technologies. You can also target .is-disabled which gets added as a class based on the same conditions that set aria-disabled.

Parameters

  • invalid Boolean? Whether or not a related form is invalid (will set aria-disabled when true)
  • pristine Boolean? Whether or not a related form is pristine (will set aria-disabled when true)
  • variant String A descriptive string that will be appended to the button's class with format button-<type> (optional, default "primary")
  • submitting Boolean? Whether or not a related form is submitting (will give button class 'in-progress when true)
  • type Boolean The type attribute of the button element (optional, default "button")
  • children Function? Any React component(s) being wrapped by the button

Examples

function MessageButton ({ message }) {
  return (
     <Button
       variant="secondary"
       onClick={ () => console.log(message) }
     >
       Print Message
     </Button>
  )
}

// For a more in-depth example of using buttons with forms, see the docs for SubmitButton.

ButtonArea

A layout component that wraps its children in a div with class button-area. This component may be used to help style forms.

If a className is provided to the component, it will be appended to the default class (see example).

Parameters

  • className String? A class to add to the wrapper
  • children Function? The React component(s) being wrapped

Examples

function ButtonForm ({ handleSubmit }) {
  return (
    <form onSubmit={ handleSubmit }>
      <ButtonArea className="my-area">
        <Button> Cancel </Button>
        <Button> Submit </Button>
      </ButtonArea>
    </form>
  )
}

// Buttons will be wrapped in a div with class: "button-area my-area"

SubmitButton

A wrapper around the Button component that adds type="submit". Generally used in the context of forms.

With the exception of type, this component shares the same props as Button.

Examples

function PersonForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field name="name" component={ Input } />
      <Field name="age" component={ Input } type="number" />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

// When SubmitButton is pressed, form will submit and handleSubmit() will be called.

Checkbox

A checkbox input that can be used in a redux-form-controlled form.

This input only accepts and stores boolean values.

Parameters

Examples

function CoolPersonForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field name="isCool" component={ Checkbox } />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default CoolPersonForm

CheckboxGroup

A group of checkboxes that can be used in a redux-form-controlled form.

The value of each checkbox is specified via the options prop. This prop can either be:

  • An array of strings
  • An array of numbers
  • An array of key-value pairs: { key, value }

The value of the entire CheckboxGroup component is an array containing the values of the selected checkboxes (converted to strings). Clicking an unselected checkbox adds its value to this array, and clicking a selected checkbox removes its value from this array.

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • options Array An array of checkbox values (strings, numbers, or key-value pairs)
  • checkboxInputProps Object An object of key-value pairs representing props to pass down to all checkbox inputs (optional, default {})
  • dropdown Boolean A flag indicating whether the checkbox options are displayed in a dropdown container or not (optional, default false)

Examples

function TodoForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="completedTodos"
         component={ CheckboxGroup }
         options={[
           'Eat breakfast',
           'Respond to emails',
           'Take out the trash',
         ]}
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default TodoForm
function TodoForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="completedTodos"
         component={ CheckboxGroup }
         options={[
           'Eat breakfast',
           'Respond to emails',
           'Take out the trash',
         ]}
         checkboxInputProps={{
           className: 'checkbox-input--secondary',
         }}
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default TodoForm

CloudinaryFileInput

A wrapper around a file input component (defaults to FileInput) that automatically uploads files to cloudinary via the cloudinaryUploader HOC.

The value of this input will only get set upon successful upload. The shape of the value will be of a file object or an array of file objects with the url set to the public URL of the uploaded file. The full response from Cloudinary is accessible via the value's meta.cloudinary key.

Additionally, the uploadStatus passed down from cloudinaryUploader will be added as a class on the input.

You can pass arguments to the instance of cloudinaryUploader via this component's props, or via the CLOUDINARY_CLOUD_NAME and CLOUDINARY_BUCKET env vars (recommended).

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • fileInput Function A component that gets wrapped with Cloudinary upload logic (optional, default FileInput)
  • multiple Boolean A flag indicating whether or not to accept multiple files (optional, default false)
  • onUploadSuccess Function A handler that gets invoked with the response from a successful upload to Cloudinary (optional, default noop)
  • onUploadFailure Function A handler that gets invoked with the error from a failed upload to Cloudinary (optional, default noop)

Examples

function HeadshotForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="headshotUrl"
         component={ CloudinaryFileInput }
         cloudName="my-cloudinary-cloud"
         bucket="my-cloudinary-bucket"
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

ColorInput

An color input that can be used in a redux-form-controlled form. The value of this input is a hex color string.

Parameters

Examples

function UserForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="favoriteColor"
         component={ ColorInput }
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

DateInput

An input component that wraps a DatePicker component from the react-datepicker library. This wrapper adds the following functionality to DatePicker:

  • Adapts it to receive redux-form-style input props.
  • Adds name and error labels.

With the exception of the input and meta props, all props are passed down to the DatePicker component. A full list of props supported by this component can be found here. Note that unfortunately aria-* props are not supported.

Note: this component requires special styles in order to render correctly. To include these styles in your project, follow the directions in the main README file.

Parameters

Examples

function BirthdayForm ({ handleSubmit }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="birthday"
         component={DateInput}
         placeholderText="mm/dd/yyyy"
       />
    </form>
  )
}

// Will render datepicker with label "Birthday" and placeholder "mm/dd/yyyy"

FileInput

A file input that can be used in a redux-form-controlled form. The value of this input is an array of file objects, with the url set to the base64 encoded data URL of the loaded file(s) by default.

Allowing multiple files to be selected requires setting the multiple prop to true. Multiple files can then be uploaded either all at once or piecemeal. This is different than the standard behavior of a file input, which will replace any existing files with whatever is selected. Once a file has been read successfully, it is possible to remove the file object from the current set of files. An optional callback can be fired when a file is removed: onRemove(removedFile). To customize the component that receives this onRemove handler, pass in a custom component to the removeComponent prop.

By default, this component displays a thumbnail preview of the loaded file(s). This preview can be customized by using the thumbnail or hidePreview props, as well as by passing a custom preview via previewComponent or children.

A component passed using previewComponent will receive the following props:

  • file: the current value of the input (an array of file objects)

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • readFiles Function A callback that is fired with new files and is expected to return an array of file objects with the url key set to the "read" value. This can be either a data URL or the public URL from a 3rd party API (optional, default readFilesAsDataUrls)
  • multiple Boolean A flag indicating whether or not to accept multiple files (optional, default false)
  • accept String? Value that defines the file types the file input should accept (e.g., ".doc,.docx"). More info: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept
  • capture ("user" | "environment")? Value that specifies which camera to use, if the accept attribute indicates the input type of image or video. This is not available for all devices (e.g., desktops). More info: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#capture
  • onRemove Function A callback fired when a file is removed (optional, default noop)
  • previewComponent Function A custom component that is used to display a preview of each attached file (optional, default RenderPreview)
  • removeComponent Function A custom component that receives value and onRemove props (optional, default RemoveButton)
  • thumbnail String? A placeholder image to display before the file is loaded
  • hidePreview Boolean A flag indicating whether or not to hide the file preview (optional, default false)
  • selectText String? An override for customizing the text that is displayed on the input's label. Defaults to 'Select File' or 'Select File(s)' depending on the multiple prop value

Examples

function HeadshotForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="headshot"
         component={ FileInput }
         selectText="Select profile picture"
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

HiddenInput

An Input component that is hidden from the page. The input element is hidden with CSS instead of using type="hidden so that Cypress can still access its value.

Aside from being hidden, this component is identical to Input, and will take the same props.

Examples

// Let's say we want the user ID to be included in the form submission,
// but we don't want it to be editable:

function UserForm ({ handleSubmit }) {
  return (
    <form onSubmit={ handleSubmit }>
       <Field name="user.name" component={ Input } />
       <Field name="user.id" component={ HiddenInput } />
    </form>
  )
}

Input

An input element that can be used in a redux-form-controlled form.

Note: The input tag is surrounded by a div with class "input-wrapper". Any children passed to this component will be rendered within this wrapper.

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • type String? A string to specify the type of input element (defaults to text)

Examples

function UserForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="firstName"
         component={ Input }
         placeholder="Your first name"
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

IconInput

A wrapper around the Input component that adds an icon to the input.

This icon is rendered as an <i> tag, with a dynamic class based on the icon prop. For example, given an icon prop of "twitter", the component will render an Input with child <i className="twitter-icon"/>.

Additionally, the wrapping div of this Input will be given the class "icon-label" for styling purposes.

Parameters

  • icon String The name of the icon associated with the input

Examples

function TwitterForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="handle"
         component={ IconInput }
         icon="twitter"
         placeholder="Your twitter handle"
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

MaskedInput

A masked input that can be used in a redux-form-controlled form. Built on top of cleave.js.

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • maskOptions Object An object of options to pass to the underlying Cleave instance. (supported options) (optional, default {})
  • onInit Function A function that will be invoked with the object representing the class when the input is initialized (optional, default null)
  • htmlRef (Function | Object) A stable reference that can be used to access the DOM node of the underlying input (optional, default null)

Examples

function PurchaseForm ({ handleSubmit, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="quantity"
         component={ MaskedInput }
         maskOptions={{ numeral: true }}
      />
      <SubmitButton submitting={submitting}>
        Submit
      </SubmitButton>
    </form>
  )
}

RangeInput

A range input that can be used in a redux-form-controlled form.

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • min Number The minumum attribute of the slider control (optional, default 0)
  • max Number The maximum attribute of the slider control (optional, default 100)
  • step Number The step attribute of the slider control (optional, default 1)
  • hideRangeValue Boolean A boolean representing whether or not to display the range value (optional, default false)

Examples

function StudentForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="minGPA"
         component={ RangeInput }
         step={ 0.5 }
         min={ 2.0 }
         max={ 4.0 }
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

RadioGroup

A group of radio buttons that can be used in a redux-form-controlled form.

The value of each radio button is specified via the options prop. This prop can either be:

  • An array of strings
  • An array of numbers
  • An array of booleans
  • An array of key-value pairs: { key, value }, where key is a string and value is a string, number, or boolean

The value of the entire RadioGroup component is the value of the currently selected radio button (converted to a string).

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • options Array An array of radio button values (strings, numbers, booleans, or key-value pairs)
  • radioInputProps Object An object of key-value pairs representing props to pass down to all radio inputs (optional, default {})

Examples

function FavoriteFoodForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="favoriteFood"
         component={ RadioGroup }
         options={[
           'Bananas',
           'Pineapples',
           'Potatoes',
         ]}
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default FavoriteFoodForm
function FavoriteFoodForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="favoriteFood"
         component={ RadioGroup }
         options={[
           'Bananas',
           'Pineapples',
           'Potatoes',
         ]}
         radioInputProps={{
           className: 'radio-input--secondary',
         }}
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default FavoriteFoodForm

Select

A select input that can be used in a redux-form-controlled form.

The value of each option is specified via the options or the optionGroups prop. The options prop will be ignored if optionGroups is present.

The options prop can either be:

  • An array of strings
  • An array of numbers
  • An array of key-value pairs: { key, value }

The optionGroups props must be an array of objects with the following keys:

  • name: The name of the option group
  • options: As above, an array of strings or key-value pairs.

The value of the Select component will be the same as the value of the selected option (converted to a string).

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • options Array An array of option values (strings, numbers, or key-value pairs). This prop will be ignored if optionGroups is present.
  • optionGroups Array An array of option group objects
  • placeholder String A string to display as a placeholder option. Pass in false to hide the placeholder option. (optional, default 'Select')
  • enablePlaceholderOption Boolean A flag indicating that the placeholder option should not be disabled (optional, default false)

Examples

// With string options

function PaintColorForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="paintColor"
         component={ Select }
         options={[
           'Purple',
           'Green',
           'Magenta',
         ]}
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

// With object options

function EmployeeForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="employeeId"
         component={ Select }
         options={[
           { key: 'Janet', value: 100 },
           { key: 'Bob', value: 101 },
         ]}
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

Switch

A switch input that can be used in a redux-form-controlled form.

This input only accepts and stores boolean values.

See the react-switch documentation for additional styling properties.

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • checkedIcon (Element | Boolean) An icon displayed when the switch is checked. Set to false if no check icon is desired.
  • uncheckedIcon (Element | Boolean) An icon displayed when the switch is unchecked. Set to false if no uncheck icon is desired.

Examples

function CoolPersonForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field name="isCool" component={ Switch } />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default CoolPersonForm

Textarea

A textarea input that can be used in a redux-form-controlled form. Can forward ref down to textarea input and optionally displays a character count.

Parameters

  • input Object A redux-form input object
  • meta Object A redux-form meta object
  • maxLength Number? The maximum allowed length of the input
  • hideCharacterCount Boolean Whether to hide the character count if given a maxLength (optional, default false)
  • forwardedRef Ref? A ref to be forwarded to textarea input (standard ref cannot currently be forwarded)

Examples

function BiographyForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field
         name="biography"
         component={ Textarea }
         maxLength={ 1000 }
      />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

ErrorLabel

A label for displaying error message.

Parameters

  • children String A message to display

Examples

function MyView () {
  const [errorMessage, setErrorMessage] = useState()
  return (
     <div>
      <button onClick={ () => doSomething().catch(setErrorMessage) }>
         Do something
      </button>
     {
       errorMessage && <ErrorLabel>{ errorMessage }</ErrorLabel>
     }
    </div>
  )
}

InputError

A dynamic error label associated with an input component.

NOTE: direct use of this component is deprecated as of v4.1.0 due to its dependency on redux-form. Please use ErrorLabel instead.

This component is used within LabeledField, and therefore is incorporated into most lp-components input components by default.

The error label uses the following rules to determine how it will be displayed:

  • If the input is invalid and touched, the label will be shown
  • If the error prop is set to a string, the label will display that text
  • If the error prop is set to an array of strings, the label will display those errors separated by commas

This label supports accessibility by adding a uniquely generated id to the span which should be referenced by the input using aria-describedby.

In addition to the props below, any extra props will be passed directly to the inner <span> element.

Parameters

  • error (String | Array) An error message or array of error messages to display
  • invalid Boolean Whether the associated input has an invalid value
  • touched String Whether the associated input has been touched
  • name String The name of the input (used to generate a unique ID)

Examples

// A custom input to use with redux-form

function ValidatedInput ({
  input: { name, value, onBlur, onChange },
  meta: { error, touched, invalid },
}) {
  return (
     <div>
      <input {...{
         name,
         value,
         onBlur,
         onChange,
      }}
      <InputError { ...{ error, invalid, touched, name } } />
    </div>
  )
}

InputLabel

A dynamic label associated with an input component.

This component is used within LabeledField, and therefore is incorporated into most lp-components input components by default.

The text of the label is set using the following rules:

  • If the label prop is set to false, the label is hidden completely
  • Else If the component is passed children, the children will be displayed within the label
  • Else If the label prop is set to a string, the label will display that text
  • Otherwise, the label will be set using the name prop.

If name is used to set the text, it will be stripped of its prefixes and converted to start case.

For instance: 'person.firstName' becomes 'First Name'

Note: When using third party form libraries (e.g., Redux Form), it's likely that setting the required prop will turn on the browser's automatic validation, which could cause the library to behave unexpectedly. If the browser validation behavior is causing issues, then add a noValidate prop to the form to turn off automatic validation. (e.g., <form noValidate></form>)

Parameters

  • name String The name of the associated input
  • id String The id of the associated input (optional, default name)
  • hint String? A usage hint for the associated input
  • label (String | Boolean)? Custom text for the label
  • tooltip String? A message to display in a tooltip
  • required Boolean A boolean value to indicate whether the field is required (optional, default false)
  • requiredIndicator String Custom character to denote a field is required (optional, default '')

Examples

// A custom input to use with redux-form

function EmailInput ({
  input: { name, value, onBlur, onChange },
  label,
}) {
  return (
     <div>
      <InputLabel name={name} label={label} />
      <input {...{
         type: 'email',
         name,
         value,
         onBlur,
         onChange,
      }}
    </div>
  )
}

LabeledField

A wrapper for redux-form controlled inputs. This wrapper adds a label component (defaults to InputLabel) above the wrapped component and an error component below (defaults to InputError). Additionally, it adds the class "error" to the wrapper if the input is touched and invalid.

In order to populate the InputLabel and InputError correctly, you should pass all the props of the corresponding input to this component. To prevent label-specific props from being passed to the input itself, use the omitLabelProps helper.

Parameters

  • hideErrorLabel Boolean A boolean determining whether to hide the error label on input error (optional, default false)
  • labelComponent Function A custom label component for the input (optional, default InputLabel)
  • errorComponent Function A custom error component for the input (optional, default InputError)
  • as String A string that determines the element type of the wrapper (optional, default 'div')

Examples

// A custom input to use with redux-form

function LabeledPhoneInput (props) {
  const {
     input: { name, value, onBlur, onChange },
     ...rest,
  } = omitLabelProps(props)
  return (
     <LabeledField { ...props }>
       <input {...{
         type: 'phone',
         name,
         value,
         onBlur,
         onChange,
         ...rest,
       }}
    </LabeledField>
  )
}

// A custom label to pass in as a label component (using <InputLabel /> and redux-form)

import LabeledPhoneInput from './LabeledPhoneInput'
import { InputLabel } from 'lp-components'
import { Field } from 'redux-form'

function CustomLabelComponent ({ onClickLabel, ...rest }) {
 return (
   <InputLabel { ...rest }>
     I agree to the <button onClick={ onClickLabel }>Terms and Conditions</button>
   </InputLabel>
 )
}

<Field
  name="phoneNumber"
  component={ LabeledPhoneInput }
  onClickLabel={ () => 'bar' }
  labelComponent={ CustomLabelComponent }
/>

FieldsetLegend

A legend representing a caption for the content of its parent field set element

This component must be used as a direct child and the only legend of the

element that groups related controls

The text of the legend is set using the following rules:

  • If the label prop is set to false, the legend is hidden visually via a class. Note: It's your responsibility to make sure your styling rules respect the visually-hidden class
  • Else If the label prop is set to a string, the label will display that text
  • Otherwise, the label will be set using the name prop.

Parameters

  • name String The name of the associated group
  • hint String? A usage hint for the associated input
  • label (String | Boolean)? Custom text for the legend
  • required Boolean A boolean value to indicate whether the field is required (optional, default false)
  • requiredIndicator String Custom character to denote a field is required (optional, default '')

Examples

function ShippingAddress (props) {
  const name = 'shippingAddress'
  return (
     <fieldset>
      <FieldsetLegend name={name} />
      <Input id={`${name}.name`} input={{name: 'name'}} />
      <Input id={`${name}.street`} input={{name: 'street'}} />
      <Input id={`${name}.city`}" input={{name: 'city'}} />
      <Input id={`${name}.state`} input={{name: 'state'}} />
    </fieldset>
  )
}

blurDirty

A function that returns an HOC to wrap a redux-form-controlled input.

If the input is pristine, this HOC replaces the passed onBlur with an empty function. This prevents the form from being re-validated unless its value has changed. This behavior can be overridden by passing the wrapped component an alwaysBlur prop with the value true.

Note: every input in lp-components has been wrapped in this HOC.

Examples

function TextForm ({ handleSubmit, pristine, invalid, submitting }) {
  return (
    <form onSubmit={ handleSubmit }>
      <Field name="text" component={ Input } />
      <SubmitButton {...{ pristine, invalid, submitting }}>
        Submit
      </SubmitButton>
    </form>
  )
}

export default compose(
   blurDirty()
)(TextForm)

convertNameToLabel

A helper function to transform a redux-form field name into a label string by stripping its namespace and converting it to start case.

Parameters

  • name String A redux-form field name

Examples

convertNameToLabel('example') // -> 'Example'
convertNameToLabel('person.firstName') // -> 'First Name'

Returns String A user-friendly field label

fieldOptionsType

A constant representing the PropTypes of the options prop for select components, e.g., Select and CheckboxGroup

Type: PropTypes

fieldOptionGroupsType

A constant representing the PropTypes of the optionGroups prop for select components, e.g., Select

Type: PropTypes

fieldPropTypesWithValue

A function that takes PropTypes for a redux-form input object. Returns an object containing all PropTypes for redux-form Field components.

Parameters

  • value PropTypes PropTypes object

Examples

const valuePropType = PropTypes.string

fieldPropTypesWithValue(valuePropType)

// {
//   input: PropTypes.shape({
//     value: PropTypes.string.isRequired,
//     name: PropTypes.string.isRequired,
//     onBlur: PropTypes.func,
//     onChange: PropTypes.func
//   }),
//   meta: PropTypes.shape({
//     dirty: PropTypes.bool,
//     invalid: PropTypes.bool,
//     pristine: PropTypes.bool,
//     touched: PropTypes.bool,
//     valid: PropTypes.bool,
//   }).isRequired
// }

Returns Object PropTypes for redux-form input and meta objects

defaultValueTypes

A constant representing default PropTypes for redux-form Field values. Default types are either number or string.

Type: PropTypes

fieldPropTypes

An object containing the default PropTypes for redux-form Field components.

Type: Object

radioGroupPropTypes

A constant representing the PropTypes of the input prop for the radio group component, e.g., RadioGroup

Type: PropTypes

checkboxGroupPropTypes

A constant representing the PropTypes of the input prop for checkbox group components, e.g., CheckboxGroup

Type: PropTypes

omitLabelProps

A function that takes a form component props object and returns the props object with InputLabel props omitted. Created in order to prevent these props from being passed down to the input component through ...rest.

Omits the following props:

  • hint
  • tooltip
  • label
  • requiredIndicator
  • errorComponent
  • labelComponent

Parameters

Examples

const props = {
   label: 'Biography',
   hint: 'A short biography',
   tooltip: 'Help us learn more about you!',
   requiredIndicator: '*',
   maxLength: 1000
}

omitLabelProps(props)

// {
//   maxLength: 1000
// }

// Use in a form input component

function Input (props) {
   const {
     input: { name, value, onBlur, onChange },
     type,
     ...rest
   } = props
   const inputProps = omitLabelProps(rest)
   return (
     ...
   )
}

Returns Object props object with InputLabel props omitted

replaceEmptyStringValue

A function that returns an HOC to wrap a redux-form-controlled input.

This HOC transforms empty string values into a different specified value. This helps inputs with non-string values avoid PropType errors when provided with the default redux-form initial value (an empty string).

Parameters

  • replacement any The value that will replace an empty string value (optional, default '')

Examples

function Checkbox ({ input: { value } }) {
  return (
    <input type="checkbox" value={ value }>
  )
}

Checkbox.propTypes = PropTypes.shape({
   input: PropTypes.shape({
     value: PropTypes.bool,
   })
})

export default compose(
   replaceEmptyStringValue(false)
)(Checkbox)

Table

A component for displaying data in a table. This component's behavior is largely determined by the TableColumn components that are passed to it.

Parameters

  • data Array An array of objects to display in the table- one object per row (optional, default [])

Examples

function PersonTable ({ people }) {
  return (
    <Table data={ people }>
      <TableColumn name="name" />
      <TableColumn name="age" label="Years alive" />
      <TableColumn name="status" component={ StatusCell } />
    </Table>
  )
}

SortableTable

A component for displaying sortable data in a table. This component's behavior is largely determined by the TableColumn components that are passed to it.

Parameters

  • data Array An array of objects to display in the table- one object per row (optional, default [])
  • initialColumn Number The name of the column that's initially selected (optional, default '')
  • initialAscending Boolean The sort direction of the initial column (optional, default true)
  • disableReverse Boolean Disables automatic reversing of descending sorts (optional, default false)
  • disableSort Boolean A flag to disable sorting on all columns and hide sorting arrows. (optional, default false)
  • controlled Boolean A flag to disable sorting on all columns, while keeping the sorting arrows. Used when sorting is controlled by an external source. (optional, default false)
  • onChange Function? A callback that will be fired when the sorting state changes
  • rowComponent Function? A custom row component for the table. Will be passed the data for the row, several internal table states (the current column being sorted (sortPath), whether ascending sort is active or not (ascending), the sorting function (sortFunc), and the value getter (valueGetter)) as well as children to render.
  • headerComponent Function? A custom header component for the table. Will be passed the configuration of the corresponding column, as well as the current sortPath / ascending and an onClick handler. May be overridden by a custom headerComponent for a column.

Examples

function PersonTable ({ people }) {
  return (
    <SortableTable data={ people } initialColumn="name">
      <TableColumn name="name" />
      <TableColumn name="age" label="Years alive" />
      <TableColumn name="status" component={ StatusCell } />
    </SortableTable>
  )
}

TableColumn

A component used to pass column information to a Table or SortableTable.

Parameters

  • name String The key of the value to display in the column from each data object
  • label String? The text that will be displayed in the column header. Defaults to name.
  • sortFunc Function? The function that will be used to sort the table data when the column is selected
  • component Function? A custom cell component for the column. Will be passed the key, name, value and data for the row.
  • headerComponent Function? A custom header component for the column. Will be passed the configuration of the column, as well as the current sortPath / ascending and an onClick handler. onClick must be appended to allow for sorting functionality.
  • onClick Function? A function that will be called onClick on every cell in the column.
  • format Function? A function that formats the value displayed in each cell in the column
  • disabled Boolean? A flag that disables sorting for the column
  • placeholder String? A string that will be displayed if the value of the cell is undefined or null
  • valueGetter Function? A function that will return a cell's value derived from each data object. Will be passed the data for the row.

Examples

function PersonTable ({ people }) {
  return (
    <SortableTable data={ people } initialColumn="name">
      <TableColumn name="name" />
      <TableColumn name="age" label="Years alive" disabled />
      <TableColumn name="status" component={ StatusCell } />
    </SortableTable>
  )
}
function CustomHeader({ column: { name }, onClick }) {
  return (
    <th onClick={onClick}>{name.toUpperCase() + '!'}</th>
  )
}

FlashMessage

A component that displays a flash message.

Parameters

  • children String The flash message that will be displayed.
  • isError Boolean A flag to indicate whether the message is an error message. (optional, default false)
  • onDismiss Function? A callback for dismissing the flash message. The dismiss button will only be shown if this callback is provided.

Examples

function MyView () {
  const [message, setMessage] = useState(null)
  return (
     <div>
       {
          message &&
          <FlashMessage>{message}</FlashMessage>)
       }
       <button onClick={() => setMessage('Hi!')}> Show message </button>
     </div>
  )
}

FlashMessageContainer

A component that displays multiple flash messages generated by redux-flash. Most apps will need only one of these containers at the top level. Will pass down any additional props to the inner FlashMessage components.

Parameters

  • messages Object The flash messages that will be displayed.
  • limit Number? Maximum number of concurrent messages to display

Examples

function MyApp ({ messages }) {
  return (
     <div>
        <FlashMessageContainer messages={ messages } />
        <RestOfTheApp />
     </div>
  )
}

Spinner

A UI component that displays a 'spinner'.

Examples

function Image ({ imgUrl }) {
  return (
     <div>
      { imgUrl
        ? <img src={ imgUrl } alt=""/>
        : <Spinner/>
      }
     </div>
  )
}

// Spinner is rendered when there is no content to display

LoadingContainer

A wrapper component that visually indicates whether a child component is loading, or loaded.

LoadingContainer renders child components with modified opacity depending on whether isLoading is true or false

Parameters

  • isLoading Boolean Whether the inner component should be indicated as loading (optional, default false)

Examples

function PatientIndex ({ patientProfiles }) {
  return (
     <div>
        <LoadingContainer isLoading={ !patientProfiles }>
          <div> Child Component </div>
        </LoadingContainer>
     </div>
  )
}

compareAtPath

A function which returns a comparison function that extracts values at a certain path, and runs given comparison function on those values.

Parameters

  • path String Name of the path to values
  • func Function Comparison function to run on values at specified path

Examples

const people = [
 { name: 'Brad', age: 66 },
 { name: 'Georgina', age: 35 }
]

const sortAscending = (a, b) => a - b

const ageComparator = compareAtPath('age', sortAscending)

people.sort(ageComparator)

// [
//   { name: 'Georgina', age: 35 },
//   { name: 'Brad', age: 66 },
// ]

Returns Function Comparison function

generateInputErrorId

A utility for generating a unique id for an input error label. This logic is centralized to facilitate reference by multiple input components.

Parameters

  • name String The name of the input

Examples

const name = 'cardNumber'

generateInputErrorId(name)

// 'cardNumberError'

Returns String String representing error id

serializeOptions

Function that transforms string options into object options with keys of key and value

Parameters

  • optionArray Array Array of option values

Examples

const options = ['apple', 'banana']

serializeOptions(options)

// [{ key: 'apple', value: 'apple' }, { key: 'banana', value: 'banana' }]

Returns Array Array of object options

serializeOptionGroups

Function that transforms options within an option group array into object options with keys of key and value

Parameters

  • optionGroupArray Array Array of option values

Examples

const optionGroups = [
 { name: 'fruits', options: ['apple', 'banana'] },
 { name: 'veggies', options: ['lettuce', 'pepper'] },
]

serializeOptionGroups(optionGroups)

// [
//   {
//     name: 'fruits',
//     options: [{ key: 'apple', value: 'apple' }, { key: 'banana', value: 'banana' }]
//   },
//   {
//     name: 'veggies',
//     options: [{ key: 'lettuce', value: 'lettuce' }, { key: 'pepper', value: 'pepper' }]
//   },
// ]

Returns Array Array of object group options

stripNamespace

A utility function to remove the leading namespace from a string. Returns the root string after the final period in a period-delineated string. Returns the argument if it is undefined or not a string.

Parameters

  • str String Namespaced string

Examples

const namespace = 'user.profile.name'

stripNamespace(namespace)

// 'name'

Returns String String with namespace removed

triggerOnKeys

Parameters

Examples

const triggerOnEnter = triggerOnKeys(() => console.log('Hi'), ['Enter'])
function MyExample () { return <Example onKeyPress={triggerOnEnter} /> }

Returns Function Returns a function that takes an event and watches for keys

Modal

A modal component with a built-in close button. Uses react-modal under the hood, and can accept any props react-modal does.

Unlike react-modal, this component does not require an isOpen prop to render. However, that prop can still be used in the case where animations are necessary- see this issue.

Note: this component requires custom styles. These styles can be imported from the lib/styles folder as shown inn the example below.

Parameters

  • onClose Function A handler for closing the modal. May be triggered via the close button, and outside click, or a key press.
  • className (String | Object) Additional class to append to the base class of the modal (modal-inner). See React Modal's style documentation for more details. (optional, default "")
  • overlayClassName (String | Object) Additional class to append to the base class of the modal overlay (modal-fade-screen). See React Modal's style documentation for more details. (optional, default "")
  • isOpen Boolean A flag for showing the modal. (optional, default true)
  • preventClose Boolean A flag for preventing the modal from being closed (close button, escape, or overlay click). (optional, default false)

Examples

// application.scss

// @import "../../node_modules/@launchpadlab/lp-components/lib/styles/modal";

// MyView.js

function MyView () {
  const [ modalShown, setModalShown ] = useState(false)
  return (
    <div>
      <button onClick={() => setModalShown(true)}>Show modal</button>
      {
         <Modal onClose={ () => setModalShown(false) }>
           This is the modal content!
         </Modal>
      }
    </div>
  )
}

cloudinaryUploader

A function that returns a React HOC for uploading files to (Cloudinary)[https://cloudinary.com].

cloudinaryUploader exposes the following props to the wrapped component:

  • upload: A function that submits a POST request to the Cloudinary endpoint with the file object and fileData.
  • uploadStatus: A string representing the status of the upload request, either uploading, upload-success, or upload-failure.

Parameters

  • cloudName string The name of the Cloudinary cloud to upload to. Can also be set via CLOUDINARY_CLOUD_NAME in process.env.
  • bucket string The name of the Cloudinary bucket to upload to. Can also be set via CLOUDINARY_BUCKET in process.env.
  • apiAdapter Object Adapter that responds to post with a Promise
  • uploadPreset string The name of the Cloudinary upload preset. Can also be set via CLOUDINARY_UPLOAD_PRESET in process.env. (optional, default default)
  • endpoint string The endpoint for the upload request. Can also be set via CLOUDINARY_ENDPOINT in process.env. (optional, default https://api.cloudinary.com/v1_1/)
  • fileType string The type of file. (optional, default auto)
  • cloudinaryPublicId string? The name of the file stored in Cloudinary.
  • createPublicId string? A function to generate a custom public id for the uploaded file. This function is passed the file object and is expected to return a string. Overridden by the cloudinaryPublicId prop.
  • requestOptions object Options for the request, as specified by (lp-requests)[https://github.com/LaunchPadLab/lp-requests/blob/master/src/http/http.js]. (optional, default DEFAULT_REQUEST_OPTIONS)

Examples

function CloudinaryFileInput ({ upload, uploadStatus, input, meta ... }) {
  const { onChange } = input
  const { submit } = meta
  return (
     <FileInput
       input={ input }
       meta={ meta }
       onLoad={ (fileData, file) => upload(fileData, file).then(() => submit(form)) }
       className={ uploadStatus }
     />
  )
}

CloudinaryFileInput.propTypes = {
  ...formPropTypes,
  upload: PropTypes.func.isRequired,
  uploadStatus: PropTypes.string.isRequired,
}

export default compose(
   cloudinaryUploader({
     cloudName: 'my-cloudinary-cloud-name',
     bucket: 'my-cloudinary-bucket',
   }),
)(CloudinaryFileInput)

Returns Function A HOC that can be used to wrap a component.