More HOCs with Recompose
item stepper, stepp through a collection
by jonahe
HTML
<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/build/Recompose.js"></script>
<div id="root"></div>
CSS
.steppers-component {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
}
.steppers {
display: flex;
width: 100%;
background-color: yellow;
}
button {
display: block;
width: 100px;
}
h3 {
width: 160px;
}
.stepper {
display: inline-flex;
flex-direction: column;
align-items: center;
border: solid 1px grey;
padding: 10px;
box-sizing: border-box;
width: 50%;
}
Babel + JSX
const { compose, withStateHandlers, branch, lifecycle, setPropTypes, mapProps, withProps} = Recompose;
/*
Handles the state needed to step through a list of items
The `itemNameSingular` will be used to create unique keys for the functions and properties
For example: a `itemNameSingular` of "person" will create keys like "personCollection", "currentPerson", "isFirstPerson", "isLastPerson", "positionOfCurrentPerson", and the methods to step back and forward ("goToPreviousPerson", "goToNextPerson")
*/
const withItemStepper = (itemNameSingular, items, shouldLoop, startIndex = 0) => {
// Building of key-names
const firstLetter = itemNameSingular[0];
const restOfLetters = itemNameSingular.slice(1, itemNameSingular.length);
const itemNameSingularLowerFirst = firstLetter.toLowerCase() + restOfLetters;
const itemNameSingularUpperFirst = firstLetter.toUpperCase() + restOfLetters;
const currentItemKeyName = `current${itemNameSingularUpperFirst}`;
const isFirstKeyName = `isFirst${itemNameSingularUpperFirst}`;
const isLastKeyName = `isLast${itemNameSingularUpperFirst}`;
const nthPositionOfCurrentItemKeyName = `positionOfCurrent${itemNameSingularUpperFirst}`;
const collectionKeyName = `${itemNameSingularLowerFirst}Collection`;
const goToPreviousKeyName = `stepToPrevious${itemNameSingularUpperFirst}`;
const goToNextKeyName = `stepToNext${itemNameSingularUpperFirst}`;
// END - Buildning of key-names
const isFirst = (collection, item) => item === collection[0];
const isLast = (collection, item) => item === collection[collection.length -1];
const indexOfItem = (collection, item) => collection.indexOf(item);
const orderOfItem = (collection, item) => indexOfItem(collection, item) +1;
const initialItem = items[startIndex];
const initialState = {
[collectionKeyName] : items,
[isFirstKeyName] : isFirst(items, initialItem),
[isLastKeyName] : isLast(items, initialItem),
[currentItemKeyName] :...