I am creating a lottery picker and i want to disable the button after selected.
I have mapped through the numbers to create the button, i am checking in the map if the number has been picked already and setting the disable to true if it has
however it does seem to work
import { useState, useEffect } from "react";
function App() {
let [lottopick, setlottopick] = useState([]);
// const [disabled, setdisabled] = useState(false);
const nums = [...Array(50).keys()].splice(1);
const lottopickfunc = (e) => {
if (lottopick.length < 6) {
setlottopick((curr) => {
return [...curr, e.target.textContent];
});
} else if (lottopick.length === 6) {
// setdisabled(true);
}
};
return (
<div className="App">
<div className="grid">
{nums.map((num) => {
return (
<button
className="grid-item"
disabled={lottopick.includes(num) ? true : false}
key={num}
onClick={lottopickfunc}
>
{num}
</button>
);
})}
</div>
</div>
);
}
export default App;
CodePudding user response:
nums is an array of numbers, while typeof e.target.textContent == "string".
[1, 2, 3].includes("2") will always be false.
CodePudding user response:
I think the problem is that your lottopick array contains strings because you're just reading e.target.textContent and then when you compare them with the values in the nums array which contains actual numbers, it never satisfies the disabled condition. For example when I pick number 24, you add '24' to lottopick and then the disabled logic becomes ['24'].includes(24) which is falsey. So the fix would be to just put actual numbers in lottopick. So Number(e.target.textContent) as opposed to e.target.textContent.
