Steps using useState Hooks in react app.
smrpdl1991
Posted on January 3, 2023
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>
);
}
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
Posted on January 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.