DEV Community

smrpdl1991
smrpdl1991

Posted on

Steps using useState Hooks in react app.

To create steps using useState in React, you can define an array of step objects in your component and use useState to keep track of the current step. You can then use this state to render the appropriate step. Here's an example of how you might do this:

import { useState } from 'react';

function Steps() {
  const steps = [
    { label: 'Step 1', component: <Step1 /> },
    { label: 'Step 2', component: <Step2 /> },
    { label: 'Step 3', component: <Step3 /> }
  ];

  const [currentStep, setCurrentStep] = useState(0);
  const currentStepData = steps[currentStep];

  return (
    <div className="steps">
      <ul>
        {steps.map((step, index) => (
          <li key={step.label} className={index === currentStep ? 'active' : ''}>
            <button onClick={() => setCurrentStep(index)}>{step.label}</button>
          </li>
        ))}
      </ul>
      {currentStepData.component}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the steps array holds the data for each step, including the label to display in the step list and the component to render for each step. The currentStep state variable is used to keep track of the current step, and the setCurrentStep function is used to update the current step when the user clicks on a different step.

The step list is rendered using the steps array, with a li element for each step. The active class is added to the li element for the current step to highlight it. The step component is rendered below the step list using the currentStepData.component value.working

Top comments (0)