- ColorPicker
- Paginator
- TabBar
- Button
- ButtonArea
- SubmitButton
- Checkbox
- CheckboxGroup
- CloudinaryFileInput
- ColorInput
- DateInput
- FileInput
- HiddenInput
- Input
- IconInput
- MaskedInput
- RangeInput
- RadioGroup
- Select
- Switch
- Textarea
- ErrorLabel
- InputError
- InputLabel
- LabeledField
- FieldsetLegend
- blurDirty
- convertNameToLabel
- fieldOptionsType
- fieldOptionGroupsType
- fieldPropTypesWithValue
- defaultValueTypes
- fieldPropTypes
- radioGroupPropTypes
- checkboxGroupPropTypes
- omitLabelProps
- replaceEmptyStringValue
- Table
- SortableTable
- TableColumn
- FlashMessage
- FlashMessageContainer
- Spinner
- LoadingContainer
- compareAtPath
- generateInputErrorId
- serializeOptions
- serializeOptionGroups
- stripNamespace
- triggerOnKeys
- Modal
- cloudinaryUploader
A control component for picking a hex color value. Built using the react-color ChromePicker
.
value
String? The hex value of the selected coloronChange
Function? A function called with the new hex value when a color is selectedonOpen
Function? A function called when the picker is expandedonClose
Function? A function called when the picker is closedactive
Boolean? A boolean that controls whether the picker is expanded or not.
function BackgroundSetter ({ backgroundColor, setBackgroundColor }) {
return (
<div>
<h1> Set background color </h1>
<ColorPicker
value={ backgroundColor }
onChange={ setBackgroundColor }
/>
</div>
)
}
A control component for navigating between multiple numbered pages.
value
Number The number of the current page (optional, default1
)onChange
Function? A function called with the new value when a page is clicked.min
Number The number of the first page (optional, default1
)max
Number The number of the last page. (optional, default1
)alwaysShow
Boolean Always show the component, even when there's only one page visible. (optional, defaultfalse
)pagesShown
Number The number of pages to display around (and including) the current page (optional, default3
)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'...'
)
function ShowPages ({ pages, currentPage, changeCurrentPage }) {
return (
<div>
<Page
page={pages[currentPage]}
/>
<Paginator
value={currentPage}
onChange={changeCurrentPage}
max={pages.length}
/>
</div>
)
}
A control component for navigating among multiple tabs
vertical
Boolean A boolean setting theclassName
of theul
to 'horizontal' (default), or 'vertical', which determines the alignment of the tabs (optional, defaultfalse
)options
Array An array of tab values (strings or key-value pairs)value
(String | Number) The value of the current tabonChange
Function? A function called with the new value when a tab is clickedactiveClassName
String The class of the active tab (optional, default'active'
)
function ShowTabs ({ currentTab, setCurrentTab }) {
return (
<div>
<TabBar
options={['Tab 1', 'Tab 2']}
value={currentTab}
onChange={setCurrentTab}
/>
</div>
)
}
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
.
invalid
Boolean? Whether or not a related form is invalid (will set aria-disabled whentrue
)pristine
Boolean? Whether or not a related form is pristine (will set aria-disabled whentrue
)variant
String A descriptive string that will be appended to the button's class with formatbutton-<type>
(optional, default"primary"
)submitting
Boolean? Whether or not a related form is submitting (will give button class'in-progress
whentrue
)type
Boolean The type attribute of the button element (optional, default"button"
)children
Function? Any React component(s) being wrapped by the button
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.
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).
className
String? A class to add to the wrapperchildren
Function? The React component(s) being wrapped
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"
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.
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.
A checkbox input that can be used in a redux-form
-controlled form.
This input only accepts and stores boolean values.
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
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.
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectoptions
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, defaultfalse
)
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
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).
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectfileInput
Function A component that gets wrapped with Cloudinary upload logic (optional, defaultFileInput
)multiple
Boolean A flag indicating whether or not to accept multiple files (optional, defaultfalse
)onUploadSuccess
Function A handler that gets invoked with the response from a successful upload to Cloudinary (optional, defaultnoop
)onUploadFailure
Function A handler that gets invoked with the error from a failed upload to Cloudinary (optional, defaultnoop
)
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>
)
}
An color input that can be used in a redux-form
-controlled form.
The value of this input is a hex color string.
function UserForm ({ handleSubmit, pristine, invalid, submitting }) {
return (
<form onSubmit={ handleSubmit }>
<Field
name="favoriteColor"
component={ ColorInput }
/>
<SubmitButton {...{ pristine, invalid, submitting }}>
Submit
</SubmitButton>
</form>
)
}
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.
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"
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)
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectreadFiles
Function A callback that is fired with new files and is expected to return an array of file objects with theurl
key set to the "read" value. This can be either a data URL or the public URL from a 3rd party API (optional, defaultreadFilesAsDataUrls
)multiple
Boolean A flag indicating whether or not to accept multiple files (optional, defaultfalse
)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#acceptcapture
("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#captureonRemove
Function A callback fired when a file is removed (optional, defaultnoop
)previewComponent
Function A custom component that is used to display a preview of each attached file (optional, defaultRenderPreview
)removeComponent
Function A custom component that receivesvalue
andonRemove
props (optional, defaultRemoveButton
)thumbnail
String? A placeholder image to display before the file is loadedhidePreview
Boolean A flag indicating whether or not to hide the file preview (optional, defaultfalse
)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 themultiple
prop value
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.
// 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>
)
}
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.
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objecttype
String? A string to specify the type of input element (defaults totext
)
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>
)
}
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.
icon
String The name of the icon associated with the input
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>
)
}
A masked input that can be used in a redux-form
-controlled form. Built on top of cleave.js.
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectmaskOptions
Object An object of options to pass to the underlyingCleave
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, defaultnull
)htmlRef
(Function | Object) A stable reference that can be used to access the DOM node of the underlying input (optional, defaultnull
)
function PurchaseForm ({ handleSubmit, submitting }) {
return (
<form onSubmit={ handleSubmit }>
<Field
name="quantity"
component={ MaskedInput }
maskOptions={{ numeral: true }}
/>
<SubmitButton submitting={submitting}>
Submit
</SubmitButton>
</form>
)
}
A range input that can be used in a redux-form
-controlled form.
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectmin
Number The minumum attribute of the slider control (optional, default0
)max
Number The maximum attribute of the slider control (optional, default100
)step
Number The step attribute of the slider control (optional, default1
)hideRangeValue
Boolean A boolean representing whether or not to display the range value (optional, defaultfalse
)
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>
)
}
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 }
, wherekey
is a string andvalue
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).
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectoptions
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{}
)
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
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 groupoptions
: 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).
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectoptions
Array An array of option values (strings, numbers, or key-value pairs). This prop will be ignored ifoptionGroups
is present.optionGroups
Array An array of option group objectsplaceholder
String A string to display as a placeholder option. Pass infalse
to hide the placeholder option. (optional, default'Select'
)enablePlaceholderOption
Boolean A flag indicating that the placeholder option should not bedisabled
(optional, defaultfalse
)
// 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>
)
}
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.
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectcheckedIcon
(Element | Boolean) An icon displayed when the switch is checked. Set tofalse
if no check icon is desired.uncheckedIcon
(Element | Boolean) An icon displayed when the switch is unchecked. Set tofalse
if no uncheck icon is desired.
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
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.
input
Object Aredux-form
input objectmeta
Object Aredux-form
meta objectmaxLength
Number? The maximum allowed length of the inputhideCharacterCount
Boolean Whether to hide the character count if given a maxLength (optional, defaultfalse
)forwardedRef
Ref? A ref to be forwarded totextarea
input (standardref
cannot currently be forwarded)
function BiographyForm ({ handleSubmit, pristine, invalid, submitting }) {
return (
<form onSubmit={ handleSubmit }>
<Field
name="biography"
component={ Textarea }
maxLength={ 1000 }
/>
<SubmitButton {...{ pristine, invalid, submitting }}>
Submit
</SubmitButton>
</form>
)
}
A label for displaying error message.
children
String A message to display
function MyView () {
const [errorMessage, setErrorMessage] = useState()
return (
<div>
<button onClick={ () => doSomething().catch(setErrorMessage) }>
Do something
</button>
{
errorMessage && <ErrorLabel>{ errorMessage }</ErrorLabel>
}
</div>
)
}
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
andtouched
, 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.
error
(String | Array) An error message or array of error messages to displayinvalid
Boolean Whether the associated input has an invalid valuetouched
String Whether the associated input has been touchedname
String The name of the input (used to generate a unique ID)
// 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>
)
}
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 tofalse
, 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>
)
name
String The name of the associated inputid
String The id of the associated input (optional, defaultname
)hint
String? A usage hint for the associated inputlabel
(String | Boolean)? Custom text for the labeltooltip
String? A message to display in a tooltiprequired
Boolean A boolean value to indicate whether the field is required (optional, defaultfalse
)requiredIndicator
String Custom character to denote a field is required (optional, default''
)
// 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>
)
}
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.
hideErrorLabel
Boolean A boolean determining whether to hide the error label on input error (optional, defaultfalse
)labelComponent
Function A custom label component for the input (optional, defaultInputLabel
)errorComponent
Function A custom error component for the input (optional, defaultInputError
)as
String A string that determines the element type of the wrapper (optional, default'div'
)
// 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 }
/>
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 controlsThe text of the legend is set using the following rules:
- If the
label
prop is set tofalse
, the legend is hidden visually via a class. Note: It's your responsibility to make sure your styling rules respect thevisually-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.
name
String The name of the associated grouphint
String? A usage hint for the associated inputlabel
(String | Boolean)? Custom text for the legendrequired
Boolean A boolean value to indicate whether the field is required (optional, defaultfalse
)requiredIndicator
String Custom character to denote a field is required (optional, default''
)
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>
)
}
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.
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)
A helper function to transform a redux-form field name into a label string by stripping its namespace and converting it to start case.
name
String A redux-form field name
convertNameToLabel('example') // -> 'Example'
convertNameToLabel('person.firstName') // -> 'First Name'
Returns String A user-friendly field label
A constant representing the PropTypes
of the options
prop for select components, e.g., Select and CheckboxGroup
Type: PropTypes
A constant representing the PropTypes
of the optionGroups
prop for select components, e.g., Select
Type: PropTypes
A function that takes PropTypes
for a redux-form
input object.
Returns an object containing all PropTypes
for redux-form
Field components.
value
PropTypesPropTypes
object
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
A constant representing default PropTypes
for redux-form
Field values.
Default types are either number
or string
.
Type: PropTypes
An object containing the default PropTypes
for redux-form
Field components.
Type: Object
A constant representing the PropTypes
of the input
prop for the radio group component, e.g., RadioGroup
Type: PropTypes
A constant representing the PropTypes
of the input
prop for checkbox group components, e.g., CheckboxGroup
Type: PropTypes
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
props
Object A props object
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
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).
replacement
any The value that will replace an empty string value (optional, default''
)
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)
A component for displaying data in a table. This component's behavior is largely determined by the TableColumn components that are passed to it.
data
Array An array of objects to display in the table- one object per row (optional, default[]
)
function PersonTable ({ people }) {
return (
<Table data={ people }>
<TableColumn name="name" />
<TableColumn name="age" label="Years alive" />
<TableColumn name="status" component={ StatusCell } />
</Table>
)
}
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.
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, defaulttrue
)disableReverse
Boolean Disables automatic reversing of descending sorts (optional, defaultfalse
)disableSort
Boolean A flag to disable sorting on all columns and hide sorting arrows. (optional, defaultfalse
)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, defaultfalse
)onChange
Function? A callback that will be fired when the sorting state changesrowComponent
Function? A custom row component for the table. Will be passed thedata
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 aschildren
to render.headerComponent
Function? A custom header component for the table. Will be passed the configuration of the corresponding column, as well as the currentsortPath
/ascending
and anonClick
handler. May be overridden by a customheaderComponent
for a column.
function PersonTable ({ people }) {
return (
<SortableTable data={ people } initialColumn="name">
<TableColumn name="name" />
<TableColumn name="age" label="Years alive" />
<TableColumn name="status" component={ StatusCell } />
</SortableTable>
)
}
A component used to pass column information to a Table or SortableTable.
name
String The key of the value to display in the column from each data objectlabel
String? The text that will be displayed in the column header. Defaults toname
.sortFunc
Function? The function that will be used to sort the table data when the column is selectedcomponent
Function? A custom cell component for the column. Will be passed thekey
,name
,value
anddata
for the row.headerComponent
Function? A custom header component for the column. Will be passed the configuration of the column, as well as the currentsortPath
/ascending
and anonClick
handler.onClick
must be appended to allow for sorting functionality.onClick
Function? A function that will be calledonClick
on every cell in the column.format
Function? A function that formats the value displayed in each cell in the columndisabled
Boolean? A flag that disables sorting for the columnplaceholder
String? A string that will be displayed if the value of the cell isundefined
ornull
valueGetter
Function? A function that will return a cell's value derived from each data object. Will be passed thedata
for the row.
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>
)
}
A component that displays a flash message.
children
String The flash message that will be displayed.isError
Boolean A flag to indicate whether the message is an error message. (optional, defaultfalse
)onDismiss
Function? A callback for dismissing the flash message. The dismiss button will only be shown if this callback is provided.
function MyView () {
const [message, setMessage] = useState(null)
return (
<div>
{
message &&
<FlashMessage>{message}</FlashMessage>)
}
<button onClick={() => setMessage('Hi!')}> Show message </button>
</div>
)
}
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.
messages
Object The flash messages that will be displayed.limit
Number? Maximum number of concurrent messages to display
function MyApp ({ messages }) {
return (
<div>
<FlashMessageContainer messages={ messages } />
<RestOfTheApp />
</div>
)
}
A UI component that displays a 'spinner'.
function Image ({ imgUrl }) {
return (
<div>
{ imgUrl
? <img src={ imgUrl } alt=""/>
: <Spinner/>
}
</div>
)
}
// Spinner is rendered when there is no content to display
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
isLoading
Boolean Whether the inner component should be indicated as loading (optional, defaultfalse
)
function PatientIndex ({ patientProfiles }) {
return (
<div>
<LoadingContainer isLoading={ !patientProfiles }>
<div> Child Component </div>
</LoadingContainer>
</div>
)
}
A function which returns a comparison function that extracts values at a certain path, and runs given comparison function on those values.
path
String Name of the path to valuesfunc
Function Comparison function to run on values at specified path
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
A utility for generating a unique id for an input error label. This logic is centralized to facilitate reference by multiple input components.
name
String The name of the input
const name = 'cardNumber'
generateInputErrorId(name)
// 'cardNumberError'
Returns String String representing error id
Function that transforms string options into object options with keys of
key
and value
optionArray
Array Array of option values
const options = ['apple', 'banana']
serializeOptions(options)
// [{ key: 'apple', value: 'apple' }, { key: 'banana', value: 'banana' }]
Returns Array Array of object options
Function that transforms options within an option group array into
object options with keys of key
and value
optionGroupArray
Array Array of option values
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
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.
str
String Namespaced string
const namespace = 'user.profile.name'
stripNamespace(namespace)
// 'name'
Returns String String with namespace removed
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
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.
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, defaulttrue
)preventClose
Boolean A flag for preventing the modal from being closed (close button, escape, or overlay click). (optional, defaultfalse
)
// 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>
)
}
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 aPOST
request to the Cloudinary endpoint with thefile
object andfileData
.uploadStatus
: A string representing the status of theupload
request, eitheruploading
,upload-success
, orupload-failure
.
cloudName
string The name of the Cloudinary cloud to upload to. Can also be set viaCLOUDINARY_CLOUD_NAME
inprocess.env
.bucket
string The name of the Cloudinary bucket to upload to. Can also be set viaCLOUDINARY_BUCKET
inprocess.env
.apiAdapter
Object Adapter that responds topost
with a PromiseuploadPreset
string The name of the Cloudinary upload preset. Can also be set viaCLOUDINARY_UPLOAD_PRESET
inprocess.env
. (optional, defaultdefault
)endpoint
string The endpoint for the upload request. Can also be set viaCLOUDINARY_ENDPOINT
inprocess.env
. (optional, defaulthttps://api.cloudinary.com/v1_1/
)fileType
string The type of file. (optional, defaultauto
)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 thecloudinaryPublicId
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, defaultDEFAULT_REQUEST_OPTIONS
)
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.