'How do I solve this program, trying to make a simple todo project in React
I'm still learning as you may see in my next code. I'm trying to make a simple todo project without any css. When I click on the add button the text gets added to array, but it doesnt get displayed. I get an error: https://ibb.co/zRGmykC. I'm pretty sure this is easy for someone with some experience but I need your help. The code is on the link : https://stackblitz.com/edit/react-agera5?file=src/index.js
Solution 1:[1]
You set todos as an array in App.js on line 6, however, when you call the addTodo function, you set todos as an object.
let newTodos = { id, text };
Then, in your TodoList, you try to map the results of todos, but once it's been cast as an object, map will no longer work, because map is a method only available to arrays.
Instead, you should create a temporary Array and assign it to a destructured array of your todos. You can then push your new todo into that array and then set your todos state to that temporary array.
const addTodo = (text) => {
let id = Math.floor(Math.random() * 1000);
const tempArray = [...todos];
tempArray.push({ id, text });
setTodos(tempArray);
};
Then, in your TodoList, you need to map your key and value as todo.id and todo.text
import React from 'react';
const TodoList = ({ todos }) => {
return (
<div>
{todos.map((todo) => (
<div key={todo.id}>{todo.text}</div>
))}
</div>
);
};
export default TodoList;
You were also missing a few react imports. Make sure even if you're importing {useState} you're also importing React. Here's an example of what the top of your Form should look like:
import React, { useState } from 'react';
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 | RyanY |
