I have the following ToDo component which is called from the App component. I see that the items array is being updated properly from the console logs when the Add Item button is clicked but the contents of the items are not displayed below the button.
function ToDo(){
const [items, setItems] = useState([])
const [currItem, setCurrItem] = useState('')
const handleClick = () => {
if(!currItem) return
console.log(currItem)
let temp = items
temp.push(currItem)
setItems([...temp])
console.log(items)
}
return(
<div>
<input type='text' onChange={(e) => setCurrItem(e.target.value)}/>
<br/>
<button onClick={handleClick}>Add Item</button>
<br/>
<div>
{
items.forEach(i => {
<div>{i}</div>
})
}
</div>
</div>
)
}
CodePudding user response:
hello try to change your code by adding this
{items.map((v,i) => {
return <div key={v}>{i}</div>;
})}
CodePudding user response:
There is problem with your handleClick
function try this
import React, { useState } from "react";
function ToDo() {
const [items, setItems] = useState([]);
const [currItem, setCurrItem] = useState("");
const handleClick = () => {
if (!currItem) return;
console.log(currItem);
let temp = [...items];
temp.push(currItem);
setItems(temp);
console.log(items);
};
return (
<div>
<input type="text" onChange={(e) => setCurrItem(e.target.value)} />
<br />
<button onClick={handleClick}>Add Item</button>
<br />
<div>
{items.map((i) => {
return <div>{i}</div>;
})}
</div>
</div>
);
}
export default ToDo;