I have simple list.
const [progressBar, setProgressBar] = useState([
{ isActive: false, name: "step1" },
{ isActive: false, name: "step2" },
{ isActive: false, name: "step3" },
{ isActive: false, name: "step4" },
{ isActive: false, name: "step5" },
{ isActive: false, name: "step6" },
{ isActive: false, name: "step7" },
]);
I show this list user and user able to change it.But the problem is that need to create condition when user choose minimum 2 and maximum 5 gap.
For example when page load the radio button is not picked.User can't just pick first item he need to pick second. Or if he picked second after when he want to change he can only change maximum from 2 to 7 (minimum from 2 to 4). Something like that I think I can explain logic.
const [progressBar, setProgressBar] = useState([
{ isActive: false, name: "step1" },
{ isActive: false, name: "step2" },
{ isActive: false, name: "step3" },
{ isActive: false, name: "step4" },
{ isActive: false, name: "step5" },
{ isActive: false, name: "step6" },
{ isActive: false, name: "step7" }
]);
const checkMinimumOfTwoAndMaxOfFive = (
index,
idx,
returnIsActive,
returnNonActive
) => {
if (index >= idx) {
return returnIsActive;
} else {
return returnNonActive;
}
};
return (
<div>
{progressBar.map((el, i) => (
<span
key={el.name}
className={el.isActive ? "red" : ""}
onClick={() =>
setProgressBar(
progressBar.map((item, idx) =>
checkMinimumOfTwoAndMaxOfFive(
i,
idx,
{ ...item, isActive: true },
{ ...item, isActive: false }
)
)
)
}
>
{el.name}
</span>
))}
</div>
);
First try:
I try find last isActive element and manipulate it.
const gap = array
.slice()
.reverse()
.findIndex((item) => item.isActive);
if (gap >= 4 || gap === 0 || gap === -1) {
return returnNonActive;
} else {
if (index >= idx) {
return returnIsActive;
} else {
return returnNonActive;
}
}
This doesn't work.
You could use something like this
Working code: https://codesandbox.io/s/competent-vaughan-cc2r8?file=/src/App.js:92-917
const limit = 5;
const size = 7;
const minimum = 2;
const [step, setStep] = useState(minimum - 1);
const stepUp = () => {
if (step < limit) {
setStep(step + 1);
}
};
const stepDown = () => {
if (step >= minimum) {
setStep(step - 1);
}
};
const Steps = ({ step }) => {
const Components = [];
for (let index = 0; index <= size; index++) {
Components.push(<Step name={`step${index}`} isActive={index <= step} />);
}
return Components;
};
const Step = ({ name, isActive }) => (
<span className={isActive ? "red" : ""} onClick={stepUp}>
{name}
</span>
);
return (
<div>
<Steps step={step} />
<div>
<button onClick={stepUp}>STEP UP</button>
<button onClick={stepDown}>STEP DOWN</button>
</div>
</div>
);