I'm building a to-do list and I want each list item to have a number, starting from 1. I'm using the useState hook on the counter but I can't figure out how to add new items to the array every time I click on a button. I haven't coded in months and I'm really rusty.
function Product() {
const [input, setInput] = useState("");
const [todo, setTodo] = useState([]);
const [count, setCount] = useState([]);
const addTodo = e => {
e.preventDefault();
setTodo([...todo, input]);
setCount(prevCount => [...prevCount, prevCount + 1]);
setInput("");
};
return (
<div>
<form>
<input value={input} onChange={e => setInput(e.target.value)} type='text' />
<button type='submit' onClick={addTodo}>
Add!
</button>
</form>
<h2 style={{ marginBottom: "0.5rem" }}>List of To-dos !</h2>
{todo.map(todo => (
<p>
{count.map(count => (
<p>{count}</p>
))}
{todo}
</p>
))}
</div>
);
}
I want to make it so each time I add a list item, it adds its number to the left. The first item would have 1, the second 2, etc..
prevCount => [...prevCount, prevCount + 1]instead of incrementingprevCount(a Number) by 1, you are creating an Array. It's as simple asprevCount=> prevCount + 1