Skip to content

Instantly share code, notes, and snippets.

@ethndotsh
Created January 8, 2023 01:55
Show Gist options
  • Save ethndotsh/d013e6b9f6063d922b7fc1219cc4a2fb to your computer and use it in GitHub Desktop.
Save ethndotsh/d013e6b9f6063d922b7fc1219cc4a2fb to your computer and use it in GitHub Desktop.
react-step-wizard Replacement
import React, { useState, useEffect } from "react";
import styles from "./StepWizard.module.css";
export function StepWizard({
children = [],
className = null,
initialStep = 1,
isHashEnabled = false,
isLazyMount = false,
transitions = undefined,
onStepChange = () => {},
nav = null,
}) {
useEffect(() => {
if (isHashEnabled) {
window.addEventListener("hashchange", onHashChange);
return () => {
window.removeEventListener("hashchange", onHashChange);
};
}
}, []);
const [activeStep, setActiveStep] = useState(0);
const [oldStep, setOldStep] = useState(0);
const [classes, setClasses] = useState({});
const [hashKeys, setHashKeys] = useState({});
const [namedSteps, setNamedSteps] = useState({});
const getSteps = () => React.Children.toArray(children);
const getHash = () => decodeURI(window.location.hash).replace(/^#/, "");
const currentStep = activeStep + 1;
const totalSteps = getSteps(children).length;
const isInvalidStep = (next) => next < 0 || next >= totalSteps;
useEffect(() => {
const hash = typeof window === "object" ? getHash() : "";
const children = getSteps();
children.forEach((child, i) => {
// set hash keys
setHashKeys({
...hashKeys,
[i]: (child.props && child.props.hashKey) || `step${i + 1}`,
});
setHashKeys({
...hashKeys,
[hashKeys[i]]: i,
});
// set named steps
setNamedSteps({
...namedSteps,
[i]: (child.props && child.props.stepName) || `step${i + 1}`,
});
setNamedSteps({
...namedSteps,
[namedSteps[i]]: i,
});
});
// Set activeStep to initialStep if exists
const initial = initialStep - 1;
if (initial && children[initial]) {
setActiveStep(initial);
}
// Set activeStep from hash - trumps initialStep
if (isHashEnabled && hash && hashKeys[hash] !== undefined) {
// References hashKey
setActiveStep(hashKeys[hash]);
}
// Give initial step an intro class
if (transitions) {
setClasses({
...classes,
[activeStep]: transitions.intro || "",
});
}
}, []);
const onHashChange = () => {
handleSetActiveStep(hashKeys[getHash()] || 0);
};
const handleSetActiveStep = (next) => {
const active = activeStep;
if (active === next) return;
if (isInvalidStep(next)) {
if (process.env.NODE_ENV !== "production") {
console.error(`${next + 1} is an invalid step`);
}
return;
}
const transitionClassNames = getTransitions();
if (active < next) {
// slide left
setClasses({
...classes,
[active]: transitionClassNames.exitLeft,
[next]: transitionClassNames.enterRight,
});
} else {
// slide right
setClasses({
...classes,
[active]: transitionClassNames.exitRight,
[next]: transitionClassNames.enterLeft,
});
}
setActiveStep(next);
setOldStep(active);
};
// callback for handleOnStepChange
useEffect(() => {
handleOnStepChange({
previousStep: oldStep + 1,
activeStep: activeStep + 1,
});
}, [activeStep, oldStep]);
const handleOnStepChange = (stats) => {
// User callback
onStepChange(stats);
// Update hash if prop set
if (isHashEnabled) updateHash(activeStep);
};
const updateHash = (activeStep) => {
window.location.hash = hashKeys[activeStep];
};
const getTransitions = () =>
transitions || {
enterRight: `${styles.animated} ${styles.fadeInRight}`,
enterLeft: `${styles.animated} ${styles.fadeInLeft}`,
exitRight: `${styles.animated} ${styles.fadeOutRight}`,
exitLeft: `${styles.animated} ${styles.fadeOutLeft}`,
};
// Allows for using HTML elements as a step
const isReactComponent = ({ type }) =>
typeof type === "function" || typeof type === "object";
const firstStep = () => goToStep(1);
/** Go to last step */
const lastStep = () => goToStep(totalSteps);
/** Next Step */
function nextStep() {
handleSetActiveStep(activeStep + 1);
}
// const nextStep = () => handleSetActiveStep(activeStep + 1);
/** Previous Step */
const previousStep = () => handleSetActiveStep(activeStep - 1);
/** Go to step index */
const goToStep = (step) => {
if (
isHashEnabled &&
typeof step === "string" &&
hashKeys[step] !== undefined
) {
handleSetActiveStep(hashKeys[step]);
} else {
handleSetActiveStep(step - 1);
}
};
/** Go to named step */
const goToNamedStep = (step) => {
if (typeof step === "string" && namedSteps[step] !== undefined) {
handleSetActiveStep(namedSteps[step]);
} else {
console.error(`Cannot find step with name "${step}"`);
}
};
const props = {
currentStep,
totalSteps,
nextStep,
previousStep,
goToStep,
goToNamedStep,
firstStep,
lastStep,
};
const childrenWithProps = React.Children.map(getSteps(), (child, i) => {
if (!child) return null;
props.isActive = i === activeStep;
props.transitions = classes[i];
console.log(typeof props.nextStep, "NEXTSTEP");
// Not Lazy Mount || isLazyMount && isActive
if (!isLazyMount || (isLazyMount && props.isActive)) {
return (
<Step {...props}>
{isReactComponent(child) ? React.cloneElement(child, props) : child}
</Step>
);
}
return null;
});
return (
<div className={className}>
{nav && React.cloneElement(nav, props)}
<div className={styles["step-wrapper"]}>{childrenWithProps}</div>
</div>
);
}
export const Step = ({ children = [], isActive = false, transitions = "" }) => (
<div
className={`${styles.step} ${transitions} ${
isActive ? styles.active : ""
}`.trim()}
>
{children}
</div>
);
/**
* Snippets from animate.css
* Credit goes to https://github.com/daneden
* github.com/daneden/animate.css
*/
.animated {
-webkit-animation-duration: 0.8192s;
animation-duration: 0.8192s;
-webkit-animation-fill-mode: backwards;
animation-fill-mode: backwards;
}
/** fadeInRight */
@-webkit-keyframes fadeInRight {
from {
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
to {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInRight {
from {
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
to {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
.fadeInRight {
-webkit-animation-name: fadeInRight;
animation-name: fadeInRight;
}
/** fadeInLeft */
@-webkit-keyframes fadeInLeft {
from {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
to {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInLeft {
from {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
to {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
.fadeInLeft {
-webkit-animation-name: fadeInLeft;
animation-name: fadeInLeft;
}
/** fadeOutRight */
@-webkit-keyframes fadeOutRight {
from {
opacity: 1;
}
to {
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
}
@keyframes fadeOutRight {
from {
opacity: 1;
}
to {
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
}
.fadeOutRight {
-webkit-animation-name: fadeOutRight;
animation-name: fadeOutRight;
}
/** fadeOutLeft */
@-webkit-keyframes fadeOutLeft {
from {
opacity: 1;
}
to {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
}
@keyframes fadeOutLeft {
from {
opacity: 1;
}
to {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
}
.fadeOutLeft {
-webkit-animation-name: fadeOutLeft;
animation-name: fadeOutLeft;
}
.step-wrapper {
position: relative;
}
.step {
opacity: 0;
pointer-events: none;
position: absolute;
top: 0;
width: 100%;
z-index: 0;
}
.active {
opacity: 1;
pointer-events: inherit;
position: relative;
z-index: 1;
}
@ethndotsh
Copy link
Author

Made around Next.js but should work with CRA, Vite, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment