Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!