Home > Mobile >  Cannot read properties of undefined (reading 'text')
Cannot read properties of undefined (reading 'text')

Time:06-22

I tried to call {todo.text} but the error "Cannot read properties of undefined (reading 'text')" appears, what should I do? Here's my code at TodoItem.js

import React from "react"

const TodoItem = ({todo}) => {
  return(
    <div className="todo-item">
      <div>{todo.text}</div>
      <button type="button" className="todo-btn primary">toggle</button>
    </div>
  )
}

export default TodoItem;

And here's my code from App.js

import './App.css';
import React, {useState} from "react";
import TodoList from "./components/TodoItem";
import TodoForm from "./components/TodoForm";

function App() {
  const [todos, setTodos] = useState([
    {text: "Buy Food", isCompleted: false},
    {text: "Learn React", isCompleted: false},
    {text: "Build todo app", isCompleted: false}
  ]);
  const addTodo = (value) => {
    const newTodos = [...todos, {text: value}];
    setTodos(newTodos)
  }
  return (
    <div className="app">
      <TodoList todos={todos}/>
      <TodoForm addTodo={addTodo}/>
    </div>
  );
}

export default App;

CodePudding user response:

you are passing wrong props change todo to todos

  <TodoList todos={todos}/>

  const TodoItem = ({todos}) => {

CodePudding user response:

import React from "react"

const TodoItem = ({todo}) => {
    console.log(todo)
    return(
        <div className="todo-item">
            <div>{todo.text}</div>
            <button type="button" className="todo-btn primary">toggle</button>
        </div>
    )
}
export default TodoItem


import React, {useState} from "react";
import TodoList from './components/TodoItem';
import TodoForm from "./components/TodoForm";
import './App.css';



function App() {
    const [todos, setTodos] = useState([
        {text: "Buy Food", isCompleted: false},
        {text: "Learn React", isCompleted: false},
        {text: "Build todo app", isCompleted: false}
    ]);
    const addTodo = (value) => {
        const newTodos = [...todos, {text: value}];
        setTodos(newTodos)
    }

    console.log(todos)

    return (
        <div className="app">
            <TodoList todo={todos}/>
            <TodoForm addTodo={addTodo}/>
        </div>
    );
}

export default App;

CodePudding user response:

Here are the mistakes:

  1. You're passing wrong props, so you should change => const TodoItem = ({todos}) or <TodoList todo={todos}/>
  2. The data type is an array, so you have to mapping the data before you call it, you can use method in javascript, ex: using map() method, {todos.map((todo) => (<TodoItem key{todo.id} todo={todo}/>))}
  • Related