Home>
How to delete a list clicked on the ToDo app

I am creating a todo application with React.
I created a function to add, but I am struggling with the code of the function to delete.

I tried to imitate the way of many class components on the net and incorporated them into function components.

The source code is as follows.

Thanks!

Error message
Warning: Functions are not valid as a React child.This may happen if you return a Component instead of<Component />from render.Or maybe you meant to call this function rather than return it.</code ></pre>
<strong>Applicable source code</strong>
<pre><code data-language = "App">import React from "react";
import Form from "./Form";
import List from "./List";
const App = () =>{
  const [todos, setTodos] = React.useState ([]);
  const addTodos = text =>{
    const newTodos = [... todos, text];
    setTodos (newTodos);
  };
  const removeTodos = (i) =>{
    const deleteTodos = [... todos];
    deleteTodos.splice (i, 1);
    setTodos (this.StaticRange.todos);
  };
  return (
    
      <Form addTodos = {addTodos} />
      <List todos = {todos} removeTodos = {removeTodos} />
    
  );
};
export default App;


Pass the removeTodos function created in the parent App to the grandchild Item.js in props.

import React from "react";
import Item from "./Item";
const List = (props) =>{
  const todos = props.todos.map ((todo, i) =>{
    return<Item key = {i} desc = {todo} />;
  });
  const removeTodos = props.removeTodos
return<ol>{todos} {removeTodos}</ol>;
};
export default List;
import React from "react";
import styled from "styled-components";
const Item = props =>{
  const [isDone, setIsDone] = React.useState (false);
  const toggleIsDone = () =>setIsDone (! isDone);
  const buttonText = isDone? "Return": "Done";
  const handleClick = (e) =>{
    e.preventDefault ();
    props.removeTodos ()
  }
  return (
    <li>
      <p>{props.desc}</p>
      <Button onClick = {toggleIsDone}>{buttonText}</Button>
      <Button onclick = {handleClick}>Delete</Button>
      {/ * ↑↑↑ Click and delete event handler installed * /}
    </li>
  );
};
const Button = styled.button`
  border-radius: 3px;
  border: 2px solid pink;
  color: pink;
  margin: 0 1em;
  padding: 0.25em 2em;
`;
export default Item;
  • Answer # 1

    It seems that removeTodos is not correctly passed from the

    List component to the Item component.
    I recommend passing removeTodos to the prop of the Item component in the following form.
    (Because it becomes a bucket relay, it may not be a good shape, but ...)

    // List
    const todos = props.todos.map ((todo, i) =>{
      return;
    });

    You can now use props.removeTodos in the Item component.
    (Don't forget to pass the Item key as an argument to removeTodos ())

    In addition, it seems that an error has occurred when trying to render removeTodos in the return of the List component.

      

    const removeTodos = props.removeTodos
      return {todos} {removeTodos} ;