React Removing an element from a rendered list

I am practicing stuffs in react js like, updating array, removing an array by doing onClick. I’ve followed some solutions but I didn’t get clear idea to achieve to remove an item from an rendered list. I’m having two components ‘todoform’ and ‘todolist’. All the logics are in ‘todoform’ , I’m rendering the array with help of map in ‘todolist’. I didn’t able to get ID of the clicked element. Could any one able to correct me , that what I am doing wrong in below code. Thanks in advance.

TododForm:

constructor(props) {
    super(props);
    this.state = {
      InputValue: "",
      todos: [],
    };
    console.log("intialvalue", this.state.InputValue);
  }

  handleChange(e) {
    this.setState({ InputValue: e.target.value });
  }



  handleSubmit(e) {
    e.preventDefault();
    this.setState({
      todos: [
        ...this.state.todos,
        {
          text: this.state.InputValue,
          completed: false,
          id: Math.random() * 1000,
        },
      ],
    });
    this.setState({ InputValue: "" });
  }

  deleteHnadler = () => {
    // console.log("im ckicked", e);
    const rem = this.state.todos.filter((el) => el.id !== this.state.todos.id);
    console.log("object", rem);

    // this.setState({ todos: rem });
  };

  render() {
    return (
      <div className="Todo">
        <form>
          <input
            type="text"
            value={this.state.InputValue}
            onChange={this.handleChange.bind(this)}
          ></input>
          <button onClick={this.handleSubmit.bind(this)}>Add</button>
        </form>
        <p>{this.state.InputValue}</p>
        <TodoList todos={this.state.todos} clickMe={this.deleteHnadler} />
      </div>
    );
  }

Todolost.js
 clickMe = () => {
    this.props.clickMe();
  };

  render() {
    return (
      <div>
        {this.props.todos.map((todo) => (
          <li key={todo.id} todo={todo}>
            {todo.text}
            <button>Completed</button>
            <button onClick={this.clickMe}>Delete</button>
          </li>
        ))}
      </div>
    );
  }

1 thought on “React Removing an element from a rendered list”

  1. In TodoList.js send the id in the event back to the parent component.

    clickMe = (id) => {
      this.props.clickMe(id);
    };
    
    <button onClick={() => this.clickMe(todo.id)}>Delete</button>
    

    In TodoForm.js receive that id and remove the item from array.

    deleteHnadler = (id) => {
       let todos = this.state.todos.filter((el) => el.id !== id);
       this.setState({ todos })
    };
    
    <TodoList todos={this.state.todos} clickMe={this.deleteHnadler} />
    
    Reply

Leave a Comment