- adaptToReactRouter
- adaptToReduxForm
- camelizeProps
- cloudinaryUploader
- deprecate
- getSet
- getSetPropTypes
- modal
- modifyProps
- omitProps
- withClassName
- onError
- onMount
- onOutsideClick
- onUnmount
- onUpdate
- sortable
- sortablePropTypes
- toggle
- togglePropTypes
- waitFor
- connectQuery
- connectParams
This HOC allows the creation of custom react-router
route components.
It can be used to wrap any component that returns a <Route />
tag, and will allow that component to be used interchangeably with <Route />
.
Note: only compatible with react-router
v3.
This rationale for this HOC can be found here.
function CatchallRoute ({ path, ...rest }) {
return (
<Route>
<Route path={ path } { ...rest } />
<Redirect path={ path + '/*' } to={ path } />
</Route>
)
}
export default compose(
adaptToReactRouter()
)(CatchallRoute)
A function that returns a React HOC that adapts an ordinary control component to be used with redux-form.
This HOC pulls the value
and onChange
props from the redux-form input
object and passes them as first-class props.
This means that any component that implements the value
/onChange
pattern may be wrapped by this HOC.
function MyInput ({ value, onChange }) {
return <input value={ value } onChange={ onChange } />
}
const MyAdaptedInput = adaptToReduxForm()(MyInput)
// Now, you can use it as a field in a redux-form controlled form
function MyForm ({ handleSubmit }) {
return (
<form onSubmit={ handleSubmit }>
<Field name="firstName" component={ MyAdaptedInput } />
</form>
)
}
A function that returns a React HOC that converts a component's props into camel-case. This HOC is particularly useful in conjunction with react_on_rails.
propName
(String | Array) The name(s) of the prop(s) to camelize. If no argument is provided, all props will be camelized.
function ProfileComponent ({ fullName, profilePic }) {
return (
<div>
<h1>{ fullName }</h1>
<img src={ profilePic }/>
</div>
)
}
export default compose(
camelizeProps(),
)(ProfileComponent)
// Now we can pass props { full_name, profile_pic } to the above component.
Returns Function A HOC that can be used to wrap a component.
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
.uploadPreset
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.
A function that returns a React HOC that displays a deprecation warning when a component is mounted.
If no message is provided, the default deprecation message is:
<Component.displayName> is deprecated and will be removed in the next version of this library.
message
String? A custom message to displaylog
Function A function for logging the message (optional, defaultconsole.warn
)
const MyComponent = () => <p>Hi</p>
export default deprecate('Do not use this component')(MyComponent)
// When component is mounted, console will show warning: 'DEPRECATED: Do not use this component'
A function that returns a React HOC that provides values and corresponding setter functions to the wrapped component. For each variable name given, the wrapped component will receive the following props:
<variableName>
: the value, default =null
.set<variableName>
: a function that will set the value to a given value.
getSet
also exposes a getSetPropTypes
function to automatically generate PropTypes for these props.
Options
getSet
may be passed an options object containing the following keys:
initialValues
: An object containing initial values for the variables
These options can also be passed in as props to the wrapped component.
varNames
(string | Array) A variable name or array of variable namesoptions
object Options for the HOC as specified above.
function TabBar ({ currentTab, setCurrentTab, tabs ... }) {
return (
<div>
{
tabs.map(tab =>
<Tab
key={ tab }
isActive={ tab === currentTab }
onClick={ () => setCurrentTab(tab) }
/>
)
}
</div>
)
}
TabBar.propTypes = {
...getSetPropTypes('currentTab'),
tabs: PropTypes.arrayOf(PropTypes.number),
}
export default compose(
getSet('currentTab', {
initialValues: {
currentTab: 1,
},
}),
)(TabBar)
Returns Function A HOC that can be used to wrap a component.
A function that returns propTypes for the getSet HOC.
function TabBar () { ... }
TabBar.propTypes = {
...getSetPropTypes('currentTab'),
}
export default compose(
getSet('currentTab'),
)(TabBar)
Returns Object An object of corresponding propTypes.
A function that returns a React HOC for creating modals.
Styling for the default wrapper modal can be pulled from the modal.css
file included in this library via your scss:
@import "~@launchpadlab/lp-hoc/lib/styles/modal.css";
Note: this HOC uses redux-modal
under the hood. The reducer from redux-modal
is exported for convenience as modalReducer
.
The following functions are available as static properties on the wrapped component:
show
: Shows the modal. Can be passed an object with props to be passed to the modal component. An event argument will be interpreted as an empty object.hide
: Hides the modal.destroy
: Destroys the modal state and unmounts the modal component.
name
String The name of the modal.component
(Function | Object)? A custom modal component to use to wrap your component. By default,Modal
fromreact-modal
will be used. This wrapper is passed the following props:{ warning, disableOutsideClick, show, handleHide, children }
. Ifnull
is provided, no wrapper will be used.warning
Boolean A boolean representing whether to add themodal-warning
class to the surroundingdiv
. (optional, defaultfalse
)destroyOnHide
Boolean A boolean representing whether to destroy the modal state and unmount the modal after hide. (optional, defaulttrue
)disableOutsideClick
Boolean A boolean representing whether clicking outside the modal div should hide the modal. (optional, defaultfalse
)
// Create Modal Component
function AlertModal ({ handleHide }) {
return (
<div>
<h1>I am an alert!</h1>
<div onClick={ handleHide } className="modal-close">×</div>
</div>
)
}
export default modal({ name: 'AlertModal' })(AlertModal)
// Use Modal
function Layout ({ showAlertModal }) {
return (
<div>
<AlertModal />
<button onClick={ showAlertModal }>Click Me!</button>
</div>
)
}
const mapDispatchToProps = {
showAlertModal: AlertModal.show,
}
export default compose(
connect(null, mapDispatchToProps),
)(Layout)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC that modifies a component's props using a given function.
The provided function will be called with the component's props, and should return an object that will be merged with those props.
modFunction
Function A function that modifies the component's props.
// modifyProps is used to create a custom save function by combining
// props from mapStateToProps() and mapDispatchToProps()
function SaveableProfile ({ name, save }) {
return (
<div>
<h1>{ name }</h1>
<button onClick={ save }>
Save this profile
</button>
</div>
)
}
function mapStateToProps (state) {
return {
id: selectors.profileId(state)
}
}
const mapDispatchToProps = {
saveProfile: actions.saveProfile
}
function modify ({ id, saveProfile }) {
return {
save: () => saveProfile(id)
}
}
export default compose(
connect(mapStateToProps, mapDispatchToProps),
modifyProps(modify),
)(SaveableProfile)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC that omits some or all of a component's props. Uses the lodash omit function under the hood.
propName
(String | Array) The name(s) of the prop(s) to be omitted. If none are provided, all of the props will be omitted.
function Child ({ name }) {
return <h1>{ name }</h1>
}
const NamelessChild = omitProps()(Child)
function Parent () {
return <NamelessChild name="Foo" />
}
// When parent is rendered, the <h1> will be empty.
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC that adds a default className to the wrapped React component.
This className will be extended by any additional classNames given to the component.
defaultClass
String The default class to add to the component
const Block = withClassName('section-block')('section')
const Header = withClassName('section-header')('div')
function Content () {
return (
<Block>
<Header className="highlighted">
This is some header text!
</Header>
</Block>
)
}
// This is equivalent to:
// function Content () {
// return (
// <section className="section-block">
// <div className="section-header highlighted">
// This is some header text!
// </div>
// </section>
// )
// }
A function that returns a React HOC to handle logic to be run during the componentDidCatch
lifecycle event.
NOTE: This HOC is only supported by React 16 or higher.
See also: onMount, onUnmount, onUpdate
onComponentDidCatch
(Function | String) A function or a string reference to a function that will be executed with the component's props.
function MyComponent () {
return (
...
)
}
function onComponentDidCatch (props, error, info) {
logErrorToMyService(error, info)
}
export default onError(onComponentDidCatch)(MyComponent)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC to handle logic to be run during the componentDidMount
lifecycle event.
See also: onError, onUnmount, onUpdate
onComponentDidMount
(Function | String) A function or a string reference to a function that will be executed with the component's props.
function MyComponent () {
return (
...
)
}
function componentDidMount (props) {
console.log('Our current props: ', props)
}
export default onMount(componentDidMount)(MyComponent)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC to handle logic to be run when a click occurs outside of a component.
handler
(Function | String) A function or a string reference to a function that will be executed with the component's props and the click event.
function MyComponent () {
return (
...
)
}
function handleOutsideClick (props, e) {
console.log('A click event occured!', e)
}
export default onOutsideClick(handleOutsideClick)(MyComponent)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC to handle logic to be run during the componentWillUnmount
lifecycle event.
See also: onError, onMount, onUpdate
onComponentWillUnmount
(Function | String) A function or a string reference to a function that will be executed with the component's props.
function MyComponent () {
return (
...
)
}
function componentWillUnmount (props) {
console.log('Our current props: ', props)
}
export default onUnmount(componentWillUnmount)(MyComponent)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC to handle logic to be run during the componentDidUpdate
lifecycle event.
See also: onError, onMount, onUnmount
onComponentDidUpdate
(Function | String) A function or a string reference to a function that will be passed the current props and the previous props.
function MyComponent () {
return (
...
)
}
function componentDidUpdate (currentProps, previousProps) {
console.log('Props updated!', currentProps, previousProps)
}
export default onUpdate(componentDidUpdate)(MyComponent)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC that provides a sort function the wrapped component.
Given a sortPath
, this function will compare the values of two objects at that path.
The wrapped component will receive the following props:
ascending
: a boolean indicating whether the sort is ascending or notdescending
: a boolean indicating whether the sort is descending or notsortPath
: a string indicating the current sort comparison path in dot notationsort
: a function that can be used to sort an array of objectssetAscending
: a function for settingascending
setDescending
: a function for settingdescending
setSortPath
: a function for settingsortPath
setSortFunc
: a function for setting a custom comparison function that will be used insort
sortable
also exposes a sortablePropTypes
object for these props.
Note: setSortPath()
will automatically reset ascending
to true
when the current path is changed.
Additionally, it will toggle ascending
if the same path is selected twice in a row,
unless false
is passed as the second parameter.
Options
getSet
may be passed an options object containing the following keys:
initialAscending
: Whether the sort is initially ascending (default=true
)initialSortPath
: The initialsortPath
initialSortFunc
: The initialsortFunc
onChange
: A callback that will be fired whenever the sorting state is updateddisableReverse
: disables the automatic reversing of sorted items when the sort is descending
The wrapped component may also receive these options as props.
options
object Options for the HOC as specified above.
function SortedPeopleList ({ people, sort, ascending, setAscending }) {
return (
<div>
<ol>
{
sort(people).map(person =>
<li>`${ person.name } - ${ person.age }`</li>
)
}
</ol>
<button onClick={ () => setAscending(!ascending) }>
Reverse order
</button>
</div>
)
}
SortedPeopleList.propTypes = {
...sortablePropTypes,
people: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
age: PropTypes.string.isRequired,
})),
}
export default compose(
sortable({
sortPath: 'age',
}),
)(SortedPeopleList)
Returns Function A HOC that can be used to wrap a component.
PropTypes for the sortable HOC.
function SortedPeopleList () { ... }
SortedPeopleList.propTypes = {
...sortablePropTypes,
}
A function that returns a React HOC that provides a toggle value and toggle function to the wrapped component. For each toggle name given, the wrapped component will receive the following props:
<toggleName>
: a boolean with the current state of the toggle value, default = false.
set<ToggleName>
: a function that will set the toggle value to a given boolean value.
toggle<ToggleName>
: a function that will toggle the toggle value.
Toggle also exposes a togglePropTypes
function to automatically generate PropTypes for these props.
function ComponentWithTooltip ({ message, tooltipShown, toggleTooltipShown }) {
return (
<div>
<button onClick={ toggleTooltipShown }>Click Me</button>
{
tooltipShown &&
<div className="tooltip">
{ message }
</div>
}
</div>
)
}
ComponentWithTooltip.propTypes = {
...togglePropTypes('tooltipShown'),
message: PropTypes.string.isRequired,
}
export default compose(
toggle('tooltopShown')
)(ComponentWithTooltip)
Returns Function A HOC that can be used to wrap a component.
A function that returns propTypes for the toggle HOC. For each toggle name given, the wrapped component will receive the following props:
function ComponentWithTooltip () { ... }
ComponentWithTooltip.propTypes = {
...togglePropTypes('tooltipShown'),
}
export default compose(
toggle('tooltopShown')
)(ComponentWithTooltip)
Returns Object An object of corresponding propTypes.
A function that returns a React HOC to handle renderWhen logic for loading state.
For the renderWhen param, the type can be one of the following:
- String - The name of a prop to wait for. When the prop is truthy, the component will render.
- Function - A function that recieves the component props and returns a boolean. When it returns true, the component will render.
- Array - An array of prop names to wait for. Each prop name will be evaluated using the
String
rules. - Object - An object where the keys are prop names and the values are expected values. When the prop values are equal to the expected values, the component will render.
renderWhen
(String | Function | Object) A rule indicating when the wrapped component may render.LoadingComponent
Function? A component to render during the loading state, will be passed the current props. If not provided,<div id="spinner" />
will be rendered. To hide this component, pass infalse
ornull
.
function MyComponent (name) {
return (
<p>{name}</p>
)
}
const renderWhen = 'name'
waitFor(renderWhen, MyComponent)
// When prop 'name' value evaluates to true, MyComponent will be rendered.
// Otherwise, the <Spinner /> component from `lp-components` will be rendered.
Returns Function Returns a higher order component (HOC) to handle conditional logic for loading states.
A function that returns a React HOC that converts a url's query parameters into props. This is particularly useful for applications using React Router v4, which no longer supports query parameter parsing OOTB.
mappingConfig
(Function | String | Array) A function, string, or array of strings. String arguments are interpreted as the names of props to pull from query params (note: if the camelized option is true, then the strings should be camelized accordingly).options
Object? Options for the HOCoptions.camelize
Boolean Option to camelize query parameter keys. This is true by default (optional, defaulttrue
)
function ResetPassword ({ token, resetPassword }) {
return (
<div>
<ResetPasswordForm
initialValues={ { token } }
onSubmit={ resetPassword }
/>
</div>
)
}
const mapDispatchToProps = {
resetPassword: apiActions.resetPassword,
}
export default compose(
connectQuery('token'),
connect(null, mapDispatchToProps),
)(ResetPassword)
Returns Function A HOC that can be used to wrap a component.
A function that returns a React HOC that converts a url's matched path parameters into props. This does not require a component to be directly connected to React Router and can be further nested in the component hierarchy.
Note: When composing together with other HOCs, make sure that this component is not blocked by another component that implements shouldComponentUpdate. For example, when using with a Redux connected component, the following sequence will not work.
compose( connect(...), connectParams, )
For more information: https://reacttraining.com/react-router/web/api/withRouter
mappingConfig
(Function | String | Array) A function, string, or array of strings. String arguments are interpreted as the names of props to pull from matched params. A function argument will accept params and map them to props based on the object returned by this function (see second example below).
// Example 1 - String argument
function StudentShow ({ student }) {
if (!student) return <p>Loading...</p>
return (
<div>
<h1>{ student.name }</h1>
</div>
)
}
function mapStateToProps (state) {
return {
student: selectors.student(state),
}
}
const mapDispatchToProps = {
fetchStudent: apiActions.fetchStudent,
}
function onComponentDidMount ({ id, fetchStudent }) {
return fetchStudent(id)
}
export default compose(
connectParams('id'),
connect(mapStateToProps, mapDispatchToProps),
onMount(onComponentDidMount),
)(StudentShow)
// Example 2 - Function argument
function StudentShow ({ student }) {
if (!student) return <p>Loading...</p>
return (
<div>
<h1>{ student.name }</h1>
</div>
)
}
function mapStateToProps (state) {
return {
student: selectors.student(state),
}
}
const mapDispatchToProps = {
fetchStudent: apiActions.fetchStudent,
}
function onComponentDidMount ({ id, fetchStudent }) {
return fetchStudent(id)
}
export default compose(
connectParams(({ studentId }) => ({ id: studentId })),
connect(mapStateToProps, mapDispatchToProps),
onMount(onComponentDidMount),
)(StudentShow)
Returns Function A HOC that can be used to wrap a component.