Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda