user17089667
user17089667

Reputation:

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!');
    }
  }

Upvotes: 1

Views: 3116

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

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>

Upvotes: 1

Related Questions