npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-hook-stepper

v1.0.4

Published

A simple and customizable multi-step stepper component for React using hooks.

Downloads

268

Readme

React Hook Stepper

Introduction

This library provides a powerful hook called useStepper to facilitate managing step flows in React applications. This hook offers properties and functions to create, navigate, and manipulate step states in a flexible and scalable way.


Installation

Install the library using npm:

npm i react-stepper-control

Install the library using pnpm or yarn:

pnpm i react-stepper-control
yarn add react-stepper-control

Hook Returns

stepperState

An object containing the complete state of the steps.

generalInfo

Provides general information about the process, such as:

  • totalSteps
  • currentProgress
  • completedProgress
  • canAccessProgress

steps

A list of configurations for all steps, including:

  • name: Name of the step
  • canAccess: Defines if the step can be accessed
  • canEdit: Defines if the step can be edited
  • isOptional: Indicates if the step is optional
  • isCompleted: Indicates if the step is completed

By default, the boolean values (canAccess, canEdit, isOptional, isCompleted) are set to false if not specified.

Usage Example

export const Step = ({ steps }: { steps: StepConfig[] }) => {
 const { stepperState } = useStepper({ steps });

 return (
  // Implement your component using stepperState
 );
};

generalstate

The generalState is a user-provided state that can be used to share information between steps. It can be typed using generics. Example:

interface Step1Type {
 step1: {
  test: string;
  test1: number;
 };
}

export const Step1 = () => {
 const { onNext, onPrev, activeStep } = useStepper<Step1Type>();

 const handleNext = () =>
  onNext({
   updateStepsStatus: [{ stepIndex: 1, data: { canEdit: true } }],
    onCompleteStep: (data) => console.log("Step 1 completed with data:", data),
  });

 return (
  <div>
   <h1>Step 1</h1>
   <button onClick={() => onPrev()}>Previous</button>
   <button onClick={handleNext}>Next</button>
  </div>
 );
};

Recommended Typing

Use extends to reuse the state of previous steps:

interface Step1Type {
 step1: { /* Step 1 values */ };
}

interface Step2Type extends Step1Type {
 step2: { /* Step 2 values */ };
}

interface Step3Type extends Step2Type {
 step3: { /* Step 3 values */ };
}

Alternatively, you can create separate typings for each step if preferred.

errors

  • A place where step errors are stored.
  • Users can also manually add errors.

This feature is under development.

activeStep

Provides the settings of the currently active step:

  • name
  • canAccess
  • canEdit
  • isOptional
  • isCompleted
  • index
  • isLastStep
  • isFirstStep

loading

Indicates if any asynchronous function (goToStep, onNext, onPrev) is being executed.

Functions

updateGeneralState

Updates the generalState

Example:

const updatedState = updateGeneralState({ data: { step1: { /* new values */ } } });
console.log(updatedState);

updateSteps

Updates configurations for one or more steps.

Example:

const updatedSteps = updateSteps([{ stepIndex: 2, data: { canEdit: true } }]);
console.log(updatedSteps);

onNext

Moves to the next step.

Defaults: Marks the current step as canAccess and isCompleted.

Allows updates to generalState and steps via updateGeneralStates and updateStepsStatus.

Example:

onNext({
 updateGeneralStates: { data: { step1: { /* new values */ } } },
 updateStepsStatus: [{ stepIndex: 2, data: { canEdit: true } }],
 onCompleteStep: async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  console.log("Steps data:", data);
 },
});

onPrev

Moves back to the previous step. Works similarly to onNext.

Example:

onPrev({
 updateGeneralStates: { data: { step1: { /* new values */ } } },
 updateStepsStatus: [{ stepIndex: 2, data: { canEdit: true } }],
 onCompleteStep: async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  console.log("Steps data:", data);
 },
});

goToStep

Navigates to a specific step by index. Works similarly to onNext, with the addition of the target step index.

Example:

goToStep(2, {
 updateGeneralStates: { data: { step1: { /* new values */ } } },
 updateStepsStatus: [{ stepIndex: 2, data: { canEdit: true } }],
 onCompleteStep: async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  console.log("Step 2 completed with data:", data);
 },
});

You can configure which properties to set as true or false for each function using the initial configuration when creating your component.

Example:

export const Step = ({ steps }: { steps: StepConfig[] }) => {
 const { stepperState } = useStepper({ steps, config: {
  validations: {
   goToStep: {
    canAccess: // true or false
   },
   next: {
    currentStep: {
     canAccess: // true or false
     canEdit: // true or false
     isOptional: // true or false
     isCompleted: // true or false
    },
    nextStep: {
     canAccess: // true or false
     canEdit: // true or false
     isOptional: // true or false
     isCompleted: // true or false
    }
   },
   prev: {
    currentStep: {
     canAccess: // true or false
     canEdit: // true or false
     isOptional: // true or false
     isCompleted: // true or false
    },
    prevStep: {
     canAccess: // true or false
     canEdit: // true or false
     isOptional: // true or false
     isCompleted: // true or false
    }
   },
   goToStep: {
    currentStep: {
     canAccess: // true or false
     canEdit: // true or false
     isOptional: // true or false
     isCompleted: // true or false
    },
    nextStep: {
     canAccess: // true or false
     canEdit: // true or false
     isOptional: // true or false
     isCompleted: // true or false
    }
   },
  }
 }
});

 return (
  // Implement your component using stepperState
 );
};

validations.goToStep.canAccess: Determines whether navigation to a specific step (goToStep(index)) is allowed based on the current step's state.

If true, it validates that the target step's canAccess property is true before allowing navigation. By default, this validation is always performed.

next.currentStep: Sets the properties of the current step when moving to the next step. next.nextStep: Sets the properties of the next step when advancing to it.

prev.currentStep: Sets the properties of the current step when going back to the previous step. prev.prevStep: Sets the properties of the previous step when navigating back to it.

goToStep.currentStep: Sets the properties of the current step when using goToStep(index) to navigate to a specific step.

goToStep.nextStep: Sets the properties of the target step when navigating to it with goToStep(index).

The following properties can be configured for each step:

  • canAccess Controls whether the step can be accessed.

  • canEdit Controls whether the step can be edited.

  • isOptional Indicates if the step is optional.

  • isCompleted Marks whether the step is completed.

Example:

By default, the entire process is saved in localStorage. However, if you prefer this not to happen, you can configure it using the saveLocalStorage property.

Example:

export const Step = ({ steps }: { steps: StepConfig[] }) => {
 const { stepperState } = useStepper({ steps, config: {
  config: {
   saveLocalStorage: false
  }
 }
});

 return (
  // Implement your component using stepperState
 );
};

The localStorage is automatically cleared when onNext is called during the final step. However, if you want to clear it manually, you can use the cleanLocalStorage method provided by useStepper.

cleanLocalStorage only removes the step-related information.

export const Step1 = () => {
 const { onNext, onPrev, activeStep, cleanLocalStorage } = useStepper();

 const handleCleanLocalStorage = () => {
  cleanLocalStorage();
 }

 const handleNext = () =>
  onNext({
   updateStepsStatus: [{ stepIndex: 1, data: { canEdit: true } }],
    onCompleteStep: (data) => console.log("Step 1 completed with data:", data),
  });

 return (
  <div>
   <h1>Step 1</h1>
   <button onClick={() => onPrev()}>Previous</button>
   <button onClick={handleNext}>Next</button>
   <button onClick={handleCleanLocalStorage}>Clean localStorage</button>
  </div>
 );
};

StepsWithProvider

Example of using the component, after being created on a page:

import { StepsWithProvider, useStepper, StepConfig, ValidationConfigStepper } from "react-hook-stepper";

export const CustomSteper = ({
 steps,
 title,
}: {
 steps: StepConfig[];
 title?: string;
 config: ValidationConfigStepper;
}) => {
 const { stepperState, activeStep, goToStep } = useStepper({ steps, ...config }); // Use the custom hook to manage steps, just pass the steps in main component

 return (
  <div>
   <h1>{title}</h1>
   <div>
    {stepperState.steps.map((step, index) => (
     <div key={index}>
      <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
        <div onClick={() => goToStep(index)}>
          {activeStep.index > index ? "✔" : index + 1}
        </div>
        <div>{step.name}</div>
      </div>
      {activeStep.index === index && (
        <div> {steps[activeStep.index].component}</div>
      )}
     </div>
    ))}
   </div>
  </div>
 );
};

const HomePage = () => {
 return (
  <div>
   <CustomSteper
    config={{
     // your config
    }}
    steps={[
     { name: "Step 1", component: <Step1 /> },
     { name: "Step 2", component: <Step2 /> },
     { name: "Step 3", component: <Step3 /> },
     { name: "Step 4", component: <Step4 />, isOptional: true },
    ]}
   />
  </div>
 );
};

export default StepsWithProvider(HomePage); // remember to use `StepsWithProvider` to provide the context for the entire flow