Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

47
Vistas
Use Delete Button in Child From Parent Component

I'm trying to create a basic to-do app without using other people's to-do apps. I'm trying to learn the basics of ReactJS. Right now I am struggling to delete a todo since I want to store the button within the Todo component which is a child component of the WorkSpace component.

const WorkSpace = (props) => {
      const [todos, setTodos] = React.useState([])
      
      function deletePara (index) {
               const newTodos = [... todos]
               newTodos.splice(index, 1)
               setTodos(newTodos)
      }

      return (
         <Todo />
      )
}

const Todo = (props) => {
      // Generic Stuffs
      return (
      // Generic Stuffs
         <DeleteIcon />
      )
}

const DeleteIcon = (props) => {
      return (
            <IconButton>
                 <DeleteForeverIcon />
            <IconButton />
      )
}

The DeleteIcon component uses MUI's IconButton and DeleteForeverIcon components. There is no other internal functionality.

If this general setup can't work does anyone have some alternative ideas?

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If you wanna delete a todo component, you should make a delete function and pass it to the DeleteIcon as props.

As code below, I put dummy todo data as initial state in the useState and you can add more todo data as many you want to test these code.

You should "filter" function to delete todo cuz using spread operator and splice function for it performs not that good compared to using filter.

I hope you find solution!

const WorkSpace = (props) => {
      const [todos, setTodos] = React.useState([{id: 1, title: "example"}])
      
      const handleDelete (id) {
        const newTodos = todos.filter(todo => todo.id !== id);
        setTodos(newTodos);
      }

      return (
          <>
            {todos.map(todo => <Todo key={todo.id} todo={todo} handleDelete={handleDelete}>)}
          </>
      )
}

const Todo = ({todo, handleDelete}) => {
      // Generic Stuffs
      return (
      // Generic Stuffs
         <p>{todo.title}</p>
         <DeleteIcon id={todo.id} handleDelete={handleDelete}/>
      )
}

const DeleteIcon = ({id, handleDelete}) => {
      return (
            <IconButton onClick={handleDelete(id)}>
                 <DeleteForeverIcon />
            <IconButton />
      )
}
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos