'i have created one basic react js todo function where i want to check/uncheck todo based on my todo array but getting error
i was creating one basic react js todo function where i want to check/uncheck todo-button based on my todo array where clicking on each button it will be add/remove class, but getting error message "elem.map is not a function". please feel free to edit live url it will be highly appreciated.
https://codesandbox.io/s/stupefied-zeh-kznykd?file=/src/App.js:325-329
Solution 1:[1]
Your
togglefunction only needs to accept the index as an argument.You then
mapover the status array, and set a new state.
const { useEffect, useState } = React;
function Accordion2() {
const [status, setStatus] = useState([
{
id: 0,
value: false
},
{
id: 1,
value: true
}
]);
// Pass in the index
const toggle = (i) => {
// And then `map` over the status state
// updating the objects
const mapped = status.map(todo => {
return todo.id === i ? {
...todo,
value: !todo.value
} : todo;
});
setStatus(mapped);
};
// I'm using `useEffect` here to show you the
// updated state
useEffect(() => console.log(status), [status]);
return (
<div className="button-blocks">
{status.map((elem, i) => {
return (
<button
className={elem.value && 'active'}
// Only pass in the index to `toggle`
onClick={() => toggle(i)}
>
Todo
</button>
);
})}
</div>
);
}
ReactDOM.render(
<Accordion2 />,
document.getElementById('react')
);
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andy |
