0

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>
    )
}
  • Try switching to `items.map()` instead of `items.forEach()` as `forEach` will not return anything while `map` returns a new array of the `div` elements: https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map – gloo Jun 22 '22 at 18:49
  • Tried .map() as well, still, the array items are not rendered. – Naveen Udhay Jun 22 '22 at 18:58
  • 1
    You also need to add a `return` statement to return the `div` element you created, like so: `items.map((i) => { return
    {i}
    ; })`
    – gloo Jun 22 '22 at 19:03
  • 1
    Does this answer your question? [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – pilchard Jun 22 '22 at 19:05
  • and [forEach over es6 Map in JSX](https://stackoverflow.com/questions/35590621/foreach-over-es6-map-in-jsx) – pilchard Jun 22 '22 at 19:06
  • Thanks @pilchard, makes a lotta sense now – Naveen Udhay Jun 22 '22 at 19:20

2 Answers2

1

hello try to change your code by adding this

  {items.map((v,i) => {
              return <div key={v}>{i}</div>;
            })}
Tarik Gadoumi
  • 55
  • 1
  • 4
0

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;
Aman Sadhwani
  • 2,902
  • 3
  • 16
  • 24