-3

I'm trying to do a to-do list but my problem is with splice to remove e.target.item specific. Using Angular 5 anything is easier. So any can help me with this incident, thanks.

import React, { Component } from 'react';

// Router
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      userInput: '',
    };
  }

  changeUserInput(input) {
    this.setState({
      userInput: input,
    });
  }
  addToList(input) {
    let listArray = this.state.items;
    listArray.push(input);

    this.setState({
      items: listArray,
      userInput: '',
    });
  }

  deleteTodo(index) {
    items: [];
    items.splice(index, 1);
    this.setState({ items });
  }

  // VIEW
  render() {
    return (
      <Router>
        <div className="App">
          {/* TODO LIST   */}
          <input
            type="text"
            onChange={(e) => this.changeUserInput(e.target.value)}
            value={this.state.userInput}
          />
          <button onClick={() => this.addToList(this.state.userInput)}>
            add
          </button>
          <button
            onClick={(index) => this.splice(this.state.userInput, [index, 1])}>
            remove
          </button>

          <ul>
            {this.state.items.map((val, index) => (
              <li key={index} onClick={this.deleteTodo.bind(this.index)}>
                {val}
              </li>
            ))}
          </ul>
        </div>
      </Router>
    );
  }
}

export default App;
Kartikey
  • 4,516
  • 4
  • 15
  • 40

1 Answers1

0

In the deleteTodo function, you are having a syntax error, you would have to write

deleteTodo(index) {
  const items = [...this.state.items]; 
  // Makes a copy of the array

  items.splice(index, 1);
  // Deletes an item at index

  this.setState({ items });
  // Updates the state with the new Array
}
Kartikey
  • 4,516
  • 4
  • 15
  • 40
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400