- camelizeProps
- componentWithClass
- deprecate
- flatToNested
- getDisplayName
- getSet
- modifyProps
- nestedToFlat
- omitProps
- onLoad
- onMount
- onUnmount
- onUpdate
- selectorForSlice
- sortable
- toggle
- validate
- waitForResponse
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
obj
keysToCamelize
(optional, default[]
)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.
A function that adds a default className to a React component or DOM element.
This className will be extended by any additional classNames given to the component.
Parameters
WrappedComponent
defaultClass
String The default class to add to the componentcomponent
(Function | String) The React component or DOM element that will receive the default class
Examples
const Block = componentWithClass('section', 'section-block')
const Header = componentWithClass('div', 'section-header')
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 logs a deprecation warning in the console every time a given function is called.
If you're deprecating a React component, use deprecateComponent
as indicated in the example below.
If no message is provided, the default deprecation message is:
<functionName> is deprecated and will be removed in the next version of this library.
Parameters
func
Function The function that is being deprecatedmessage
String? A custom message to displaylog
Function A function for logging the message (optional, defaultconsole.warn
)
Examples
// In my-func.js
function myFunc () {
return 'hey!'
}
export default deprecate(myFunc, 'Do not use!')
// In another file:
import myFunc from './my-func'
myFunc() // -> 'hey!'
// Console will show warning: 'DEPRECATED: Do not use!'
// If you're deprecating a React component, use deprecateComponent as an HOC:
const MyComponent = () => <p>Hi</p>
export default deprecateComponent('Do not use this component')(MyComponent)
// When component is mounted, console will show warning: 'DEPRECATED: Do not use this component'
Returns an object where the keys are converted from string paths to nested objects. This is the opposite of nestedToFlat.
Parameters
obj
Object An object of key-value pairs where the keys are strings of the formpart1[.part2, ...]
Examples
const flatObj = {
'foo.bar.baz': 'hello',
space: 'world'
}
flatToNested(flatObj)
// {
// foo: {
// bar: {
// baz: 'hello'
// }
// },
// space: 'world'
// }
Returns Object A potentially nested object
Returns the display name of a React component.
This is helpful for higher order components to call on their wrapped
component so the
name that shows up in the React Dev Tools includes the name wrapped
component making
debugging much easier.
For React classes and named functional components, the name will be returned. For inline
functional components without a name, Component
will be returned. If displayName
is
explicitly set, then that will be returned.
Parameters
Component
Function A React component
Examples
// Inline functional component
getDisplayName(() => <div></div>) // `Component`
// Named functional components
const Foo = () => <div></div>
getDisplayName(Foo) // `Foo`
function Foo () {
return <div></div>
}
getDisplayName(Foo) // `Foo`
// Class
class Foo extends React.Component {
render() {
return <div></div>
}
}
getDisplayName(Foo) // `Foo`
// Explicit `displayName`
class Foo extends React.Component {
static displayName = 'Bar'
render() { return <div></div> }
}
getDisplayName(Foo)) // `Bar`
Returns String The component name if it is possible to determine, otherwise 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.
Parameters
names
(optional, default[]
)options
object Options for the HOC as specified above. (optional, default{}
)varNames
(string | Array) A variable name or array of variable names
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', {
intialValues: {
currentTab: 1,
},
}),
)(TabBar)
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.
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.
Returns an object where the keys are string paths converted from nested objects. This is the opposite of flatToNested.
Parameters
obj
Object A nested objectprefix
String? A string prefix to prepend to the keys of root object, typically only used internally. (optional, defaultnull
)
Examples
const nestedObj = {
foo: {
bar: {
baz: 'hello'
}
},
space: 'world'
}
nestedToFlat(nestedObj)
// {
// 'foo.bar.baz': 'hello',
// }
Returns Object An object of key-value pairs where the keys are strings of the form part1[.part2, ...]
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
options
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.
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 defined and not equal to 'loading', 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,<p>Loading...</p>
will be rendered. (optional, defaultnull
)
Examples
function MyComponent (name) {
return (
<p>{name}</p>
)
}
const renderWhen = 'name'
onLoad(renderWhen, MyComponent)
// When prop 'name' value evaluates to true, MyComponent will be rendered.
// Otherwise, <p>Loading...</p> 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 to handle logic to be run during the componentDidMount
lifecycle event.
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.
A function that returns a React HOC to handle logic to be run during the componentWillUnmount
lifecycle event.
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.
A function that returns a React HOC to handle logic to be run during the componentDidUpdate
lifecycle event.
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.
A Redux helper.
Given the path of a certain state slice, it returns a function that can be used to create state selectors (helpful for mapStateToProps()
).
Parameters
slicePath
String Path to slice of state.
Examples
import { selectorForSlice } from 'lp-utils'
const state = {
userSlice: {
user: {
name: 'test'
}
}
}
const select = selectorForSlice('userSlice')
//The resulting select() function has arguments (path, defaultValue)
const Selectors = {}
Selectors.user = select('user')
Selectors.username = select('user.name', 'defaultName')
export { Selectors }
// These selectors can be called in mapStateToProps() like so:
// Selectors.user(state) => { name: 'test' }
// Selectors.username(state) => 'test'
Returns Function A function that can be used to create state selectors.
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:
ascending
: Whether the sort is initially ascending (default=true
)sortPath
: The initialsortPath
sortFunc
: The initialsortFunc
Parameters
options
object Options for the HOC as specified above. (optional, default{}
)
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.
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>Active
: 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
toggles
...string One or more toggle names.
Examples
function ComponentWithTooltip ({ message, tooltipActive, toggleTooltip, ... }) {
return (
<div>
<button onClick={ toggleTooltip }>Click Me</button>
{
tooltipActive &&
<div className="tooltip">
{ message }
</div>
}
</div>
)
}
ComponentWithTooltip.propTypes = {
...togglePropTypes('tooltip'),
message: PropTypes.string
Returns Function A HOC that can be used to wrap a component.
A wrapper around the validate
function exported from
Validate JS to make it work seamlessly with
Redux Form.
Note: this function is deprecated and will be removed in the next major version. Import it from @launchpadlab/lp-form
instead.
Parameters
constraints
Object A 'flat' object containing constraints in the format specified by Validate JS. These are key-value pairs where the keys correspond to keys in the data that will be validated. This is a 'flat' object in that nested data must be accessed using a string path (ex. 'foo.bar') as the key.
Examples
const data = {
name: 'Foo',
address: {
zip: '12'
}
}
const constraints = {
name: {
presence: true
},
'address.zip': {
presence: true,
length: { is: 5 }
}
}
validate(constraints)(data)
// {
// address: {
// zip: ['Zip is the wrong length (should be 5 characters)']
// }
// }
Returns Function validate - A function that takes an object of data to be validated and returns a 'nested' object containing errors in the format specified by Redux Form.
A function that returns an HOC to handle rendering that depends on an API response. A combination of onLoad and selectors from lp-redux-api.
Parameters
requestKeys
(String | Array) A key or set of keys corresponding tolp-redux-api
requests. (optional, default[]
)LoadingComponent
Function A component to render during the loading state. (optional, defaultnull
)
Examples
import { REQ_USERS, requestUsers } from 'actions'
function MyComponent (name) {
return (
<p>{name}</p>
)
}
export default compose(
onMount(requestUsers),
waitForResponse(REQ_USERS),
)(MyComponent)
// requestUsers() dispatches an LP_API action with key 'REQ_USERS' on component mount.
// When the status of 'REQ_USERS' request becomes 'success' or 'failure', the component will render.
// Otherwise, the default `onLoad` loading component will be rendered.
Returns Function A higher order component (HOC).