Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

254
Vistas
How to remove a DOM component in react

I'm new to react, and I really don't understand how to make a component remove itself from the DOM.

Basically a component has an associated delete event and I want the component to delete itself after executing the process.

      async delete(){
    let request=await fetch('/admin/delete-product', {method: 'DELETE', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({productName: this.state.name})});
    let response=await request.json();
    if (response.result==='Sucess!'){
      alert('The product has been deleted!');
      //How delete the component from the DOM?
    } else{
      alert('Error. Try again!');
    }
  }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The component can't remove itself. You'd do this by telling the component's parent to remove it (to re-render without rendering the target component). There are a number of ways to do that. For instance, the parent could handle whatever event it is (a click or whatever) rather than the child handling it. Or the parent could pass a function to the child that the child uses when it knows it should be removed.

You can see this at work in any "To Do" tutorial for React. Here's a very basic unoptimized example where the parent passes a function to the child that the child uses to remove itself:

const {useState, useCallback} = React;

const Todo = ({todo, remove}) => {
    return <div>
        {todo.text}
        <span className="delete" onClick={() => remove(todo.id)}>X</span>
    </div>;
};

let nextId = 1;
const defaultTodos = [
    {text: "This", id: ++nextId},
    {text: "That", id: ++nextId},
    {text: "The other", id: ++nextId},
];
const TodoList = () => {
    const [todos, setTodos] = useState(defaultTodos);
    const [text, setText] = useState("");

    const addTodo = useCallback(() => {
        setTodos(todos => [...todos, {text, id: nextId++}]);
        setText("");
    }, [text]);

    const removeTodo = useCallback(id => {
        setTodos(todos => todos.filter(todo => todo.id !== id));
    }, []);
    
    const textChange = event => {
        setText(event.target.value);
    };

    return <div>
        <div>{todos.length
            ? todos.map(todo => <Todo key={todo.id} todo={todo} remove={removeTodo} />)
            : <em>(Nothing to do!)</em>
        }</div>
        <hr/>
        <div>
            <input type="text" value={text} onChange={textChange} />
            <input type="button" value="Add" onClick={addTodo} disabled={!text} />
        </div>
    </div>;
};

ReactDOM.render(<TodoList />, document.getElementById("root"));
.delete {
    float: right;
    cursor: pointer;
}
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda