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>
    )
}
6
  • 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: stackoverflow.com/questions/34426458/… Commented Jun 22, 2022 at 18:49
  • Tried .map() as well, still, the array items are not rendered. Commented Jun 22, 2022 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 <div>{i}</div>; }) Commented Jun 22, 2022 at 19:03
  • 1
    Does this answer your question? When should I use a return statement in ES6 arrow functions Commented Jun 22, 2022 at 19:05
  • and forEach over es6 Map in JSX Commented Jun 22, 2022 at 19:06

2 Answers 2

1

hello try to change your code by adding this

  {items.map((v,i) => {
              return <div key={v}>{i}</div>;
            })}
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.