- 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.
valueString? The hex value of the selected coloronChangeFunction? A function called with the new hex value when a color is selectedonOpenFunction? A function called when the picker is expandedonCloseFunction? A function called when the picker is closedactiveBoolean? 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.
valueNumber The number of the current page (optional, default1)onChangeFunction? A function called with the new value when a page is clicked.minNumber The number of the first page (optional, default1)maxNumber The number of the last page. (optional, default1)alwaysShowBoolean Always show the component, even when there's only one page visible. (optional, defaultfalse)pagesShownNumber The number of pages to display around (and including) the current page (optional, default3)previousLabelString The text of the "previous page" button (optional, default'Prev')nextLabelString The text of the "next page" button (optional, default'Next')delimiterString 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
verticalBoolean A boolean setting theclassNameof theulto 'horizontal' (default), or 'vertical', which determines the alignment of the tabs (optional, defaultfalse)optionsArray An array of tab values (strings or key-value pairs)value(String | Number) The value of the current tabonChangeFunction? A function called with the new value when a tab is clickedactiveClassNameString 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.
invalidBoolean? Whether or not a related form is invalid (will set aria-disabled whentrue)pristineBoolean? Whether or not a related form is pristine (will set aria-disabled whentrue)variantString A descriptive string that will be appended to the button's class with formatbutton-<type>(optional, default"primary")submittingBoolean? Whether or not a related form is submitting (will give button class'in-progresswhentrue)typeBoolean The type attribute of the button element (optional, default"button")childrenFunction? 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).
classNameString? A class to add to the wrapperchildrenFunction? 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 CoolPersonFormA 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.
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectoptionsArray An array of checkbox values (strings, numbers, or key-value pairs)checkboxInputPropsObject An object of key-value pairs representing props to pass down to all checkbox inputs (optional, default{})dropdownBoolean 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 TodoFormfunction 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 TodoFormA 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).
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectfileInputFunction A component that gets wrapped with Cloudinary upload logic (optional, defaultFileInput)multipleBoolean A flag indicating whether or not to accept multiple files (optional, defaultfalse)onUploadSuccessFunction A handler that gets invoked with the response from a successful upload to Cloudinary (optional, defaultnoop)onUploadFailureFunction 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)
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectreadFilesFunction A callback that is fired with new files and is expected to return an array of file objects with theurlkey set to the "read" value. This can be either a data URL or the public URL from a 3rd party API (optional, defaultreadFilesAsDataUrls)multipleBoolean A flag indicating whether or not to accept multiple files (optional, defaultfalse)acceptString? 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#captureonRemoveFunction A callback fired when a file is removed (optional, defaultnoop)previewComponentFunction A custom component that is used to display a preview of each attached file (optional, defaultRenderPreview)removeComponentFunction A custom component that receivesvalueandonRemoveprops (optional, defaultRemoveButton)thumbnailString? A placeholder image to display before the file is loadedhidePreviewBoolean A flag indicating whether or not to hide the file preview (optional, defaultfalse)selectTextString? An override for customizing the text that is displayed on the input's label. Defaults to 'Select File' or 'Select File(s)' depending on themultipleprop 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.
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objecttypeString? 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.
iconString 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.
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectmaskOptionsObject An object of options to pass to the underlyingCleaveinstance. (supported options) (optional, default{})onInitFunction 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.
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectminNumber The minumum attribute of the slider control (optional, default0)maxNumber The maximum attribute of the slider control (optional, default100)stepNumber The step attribute of the slider control (optional, default1)hideRangeValueBoolean 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 }, wherekeyis a string andvalueis 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).
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectoptionsArray An array of radio button values (strings, numbers, booleans, or key-value pairs)radioInputPropsObject 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 FavoriteFoodFormfunction 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 FavoriteFoodFormA 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).
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectoptionsArray An array of option values (strings, numbers, or key-value pairs). This prop will be ignored ifoptionGroupsis present.optionGroupsArray An array of option group objectsplaceholderString A string to display as a placeholder option. Pass infalseto hide the placeholder option. (optional, default'Select')enablePlaceholderOptionBoolean 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.
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectcheckedIcon(Element | Boolean) An icon displayed when the switch is checked. Set tofalseif no check icon is desired.uncheckedIcon(Element | Boolean) An icon displayed when the switch is unchecked. Set tofalseif 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 CoolPersonFormA 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.
inputObject Aredux-forminput objectmetaObject Aredux-formmeta objectmaxLengthNumber? The maximum allowed length of the inputhideCharacterCountBoolean Whether to hide the character count if given a maxLength (optional, defaultfalse)forwardedRefRef? A ref to be forwarded totextareainput (standardrefcannot 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.
childrenString 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
invalidandtouched, the label will be shown - If the
errorprop is set to a string, the label will display that text - If the
errorprop 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 displayinvalidBoolean Whether the associated input has an invalid valuetouchedString Whether the associated input has been touchednameString 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
labelprop 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
labelprop is set to a string, the label will display that text - Otherwise, the label will be set using the
nameprop.
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>)
nameString The name of the associated inputidString The id of the associated input (optional, defaultname)hintString? A usage hint for the associated inputlabel(String | Boolean)? Custom text for the labeltooltipString? A message to display in a tooltiprequiredBoolean A boolean value to indicate whether the field is required (optional, defaultfalse)requiredIndicatorString 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.
hideErrorLabelBoolean A boolean determining whether to hide the error label on input error (optional, defaultfalse)labelComponentFunction A custom label component for the input (optional, defaultInputLabel)errorComponentFunction A custom error component for the input (optional, defaultInputError)asString 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
labelprop is set tofalse, the legend is hidden visually via a class. Note: It's your responsibility to make sure your styling rules respect thevisually-hiddenclass - Else If the
labelprop is set to a string, the label will display that text - Otherwise, the label will be set using the
nameprop.
nameString The name of the associated grouphintString? A usage hint for the associated inputlabel(String | Boolean)? Custom text for the legendrequiredBoolean A boolean value to indicate whether the field is required (optional, defaultfalse)requiredIndicatorString 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.
nameString 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.
valuePropTypesPropTypesobject
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:
hinttooltiplabelrequiredIndicatorerrorComponentlabelComponent
propsObject 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).
replacementany 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.
dataArray 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.
dataArray An array of objects to display in the table- one object per row (optional, default[])initialColumnNumber The name of the column that's initially selected (optional, default'')initialAscendingBoolean The sort direction of the initial column (optional, defaulttrue)disableReverseBoolean Disables automatic reversing of descending sorts (optional, defaultfalse)disableSortBoolean A flag to disable sorting on all columns and hide sorting arrows. (optional, defaultfalse)controlledBoolean A flag to disable sorting on all columns, while keeping the sorting arrows. Used when sorting is controlled by an external source. (optional, defaultfalse)onChangeFunction? A callback that will be fired when the sorting state changesrowComponentFunction? A custom row component for the table. Will be passed thedatafor 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 aschildrento render.headerComponentFunction? A custom header component for the table. Will be passed the configuration of the corresponding column, as well as the currentsortPath/ascendingand anonClickhandler. May be overridden by a customheaderComponentfor 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.
nameString The key of the value to display in the column from each data objectlabelString? The text that will be displayed in the column header. Defaults toname.sortFuncFunction? The function that will be used to sort the table data when the column is selectedcomponentFunction? A custom cell component for the column. Will be passed thekey,name,valueanddatafor the row.headerComponentFunction? A custom header component for the column. Will be passed the configuration of the column, as well as the currentsortPath/ascendingand anonClickhandler.onClickmust be appended to allow for sorting functionality.onClickFunction? A function that will be calledonClickon every cell in the column.formatFunction? A function that formats the value displayed in each cell in the columndisabledBoolean? A flag that disables sorting for the columnplaceholderString? A string that will be displayed if the value of the cell isundefinedornullvalueGetterFunction? A function that will return a cell's value derived from each data object. Will be passed thedatafor 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.
childrenString The flash message that will be displayed.isErrorBoolean A flag to indicate whether the message is an error message. (optional, defaultfalse)onDismissFunction? 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.
messagesObject The flash messages that will be displayed.limitNumber? 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 displayA 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
isLoadingBoolean 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.
pathString Name of the path to valuesfuncFunction 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.
nameString 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
optionArrayArray 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
optionGroupArrayArray 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.
strString 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.
onCloseFunction 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"")isOpenBoolean A flag for showing the modal. (optional, defaulttrue)preventCloseBoolean 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 aPOSTrequest to the Cloudinary endpoint with thefileobject andfileData.uploadStatus: A string representing the status of theuploadrequest, eitheruploading,upload-success, orupload-failure.
cloudNamestring The name of the Cloudinary cloud to upload to. Can also be set viaCLOUDINARY_CLOUD_NAMEinprocess.env.bucketstring The name of the Cloudinary bucket to upload to. Can also be set viaCLOUDINARY_BUCKETinprocess.env.apiAdapterObject Adapter that responds topostwith a PromiseuploadPresetstring The name of the Cloudinary upload preset. Can also be set viaCLOUDINARY_UPLOAD_PRESETinprocess.env. (optional, defaultdefault)endpointstring The endpoint for the upload request. Can also be set viaCLOUDINARY_ENDPOINTinprocess.env. (optional, defaulthttps://api.cloudinary.com/v1_1/)fileTypestring The type of file. (optional, defaultauto)cloudinaryPublicIdstring? The name of the file stored in Cloudinary.createPublicIdstring? 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 thecloudinaryPublicIdprop.requestOptionsobject 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.