Skip to content

Latest commit

 

History

History
1105 lines (777 loc) · 28.1 KB

docs.md

File metadata and controls

1105 lines (777 loc) · 28.1 KB

Table of Contents

adaptToReactRouter

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.

Examples

function CatchallRoute ({ path, ...rest }) {
   return (
     <Route>
       <Route path={ path } { ...rest } />
       <Redirect path={ path + '/*' } to={ path } />
     </Route>
   )
}

export default compose(
   adaptToReactRouter()
)(CatchallRoute)

adaptToReduxForm

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.

Examples

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>
   )
}

camelizeProps

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.

Parameters

  • propName (String | Array) The name(s) of the prop(s) to camelize. If no argument is provided, all props will be camelized.

Examples

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.

cloudinaryUploader

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

cloudinaryUploader exposes the following props to the wrapped component:

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

Parameters

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

Examples

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

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

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

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

deprecate

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.

Parameters

  • message String? A custom message to display
  • log Function A function for logging the message (optional, default console.warn)

Examples

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'

getSet

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.

Parameters

  • varNames (string | Array) A variable name or array of variable names
  • options object Options for the HOC as specified above.

Examples

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.

getSetPropTypes

A function that returns propTypes for the getSet HOC.

Parameters

  • varNames (String | Array) A variable name or array of variable names.

Examples

function TabBar () { ... }

TabBar.propTypes = {
  ...getSetPropTypes('currentTab'),
}

export default compose(
   getSet('currentTab'),
)(TabBar)

Returns Object An object of corresponding propTypes.

modal

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.

Parameters

  • name String The name of the modal.
  • component (Function | Object)? A custom modal component to use to wrap your component. By default, Modal from react-modal will be used. This wrapper is passed the following props: { warning, disableOutsideClick, show, handleHide, children }. If null is provided, no wrapper will be used.
  • warning Boolean A boolean representing whether to add the modal-warning class to the surrounding div. (optional, default false)
  • destroyOnHide Boolean A boolean representing whether to destroy the modal state and unmount the modal after hide. (optional, default true)
  • disableOutsideClick Boolean A boolean representing whether clicking outside the modal div should hide the modal. (optional, default false)

Examples

// 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.

modifyProps

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.

Parameters

  • modFunction Function A function that modifies the component's props.

Examples

// 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.

omitProps

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.

Parameters

  • propName (String | Array) The name(s) of the prop(s) to be omitted. If none are provided, all of the props will be omitted.

Examples

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.

withClassName

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.

Parameters

  • defaultClass String The default class to add to the component

Examples

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>
//   )
// }

onError

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

Parameters

  • onComponentDidCatch (Function | String) A function or a string reference to a function that will be executed with the component's props.

Examples

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.

onMount

A function that returns a React HOC to handle logic to be run during the componentDidMount lifecycle event.

See also: onError, onUnmount, onUpdate

Parameters

  • onComponentDidMount (Function | String) A function or a string reference to a function that will be executed with the component's props.

Examples

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.

onOutsideClick

A function that returns a React HOC to handle logic to be run when a click occurs outside of a component.

Parameters

  • 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.

Examples

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.

onUnmount

A function that returns a React HOC to handle logic to be run during the componentWillUnmount lifecycle event.

See also: onError, onMount, onUpdate

Parameters

  • onComponentWillUnmount (Function | String) A function or a string reference to a function that will be executed with the component's props.

Examples

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.

onUpdate

A function that returns a React HOC to handle logic to be run during the componentDidUpdate lifecycle event.

See also: onError, onMount, onUnmount

Parameters

  • onComponentDidUpdate (Function | String) A function or a string reference to a function that will be passed the current props and the previous props.

Examples

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.

sortable

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 not
  • descending: a boolean indicating whether the sort is descending or not
  • sortPath: a string indicating the current sort comparison path in dot notation
  • sort: a function that can be used to sort an array of objects
  • setAscending: a function for setting ascending
  • setDescending: a function for setting descending
  • setSortPath: a function for setting sortPath
  • setSortFunc: a function for setting a custom comparison function that will be used in sort

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 initial sortPath
  • initialSortFunc: The initial sortFunc
  • onChange: A callback that will be fired whenever the sorting state is updated
  • disableReverse: disables the automatic reversing of sorted items when the sort is descending

The wrapped component may also receive these options as props.

Parameters

  • options object Options for the HOC as specified above.

Examples

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.

sortablePropTypes

PropTypes for the sortable HOC.

Examples

function SortedPeopleList () { ... }

SortedPeopleList.propTypes = {
  ...sortablePropTypes,
}

toggle

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.

Parameters

  • toggleNames (String | Array) One or more toggle names. (optional, default [])

Examples

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.

togglePropTypes

A function that returns propTypes for the toggle HOC. For each toggle name given, the wrapped component will receive the following props:

Parameters

  • toggleNames (String | Array) One or more toggle names.

Examples

function ComponentWithTooltip () { ... }

ComponentWithTooltip.propTypes = {
  ...togglePropTypes('tooltipShown'),
}

export default compose(
  toggle('tooltopShown')
)(ComponentWithTooltip)

Returns Object An object of corresponding propTypes.

waitFor

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.

Parameters

  • 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 in false or null.

Examples

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.

connectQuery

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.

Parameters

  • 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 HOC
    • options.camelize Boolean Option to camelize query parameter keys. This is true by default (optional, default true)

Examples

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.

connectParams

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

Parameters

  • 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).

Examples

// 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.