Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: e.preventDefault() is not a function

I'm making a simple todo app, where i have put in the logic to edit and delete the todos as well. I'm trying to update the parent state from child component but when i'm trying to click on delete it is throwing me an error e.preventDefault() is not a function and it is removing all of the todos here are the components:

PARENT

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       listArr: [],
    }

  }


 deleteTodos(i) {
   var lists = this.state.listArr;
   lists.splice(i, 1);
   this.setState({listArr: lists})
 }

render() {
 .......
 <ToDoList {...this.state} passDeleteTodos={this.deleteTodos} />
......

}

CHILD

export class ToDoList extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
              editing: false,
            };

        handleDelete(e, i) {
            e.preventDefault();
            this.props.passDeleteTodos()
        }


    renderDisplay() {
        return(
          <div>
           {
            this.props.listArr.map((list,i) => {
               return(
                 <div key={i} index={i} ref="text">
                  <li>{list}
                    <div style={{float: 'right'}}>
                     <button className="btn btn-danger btn-xs glyphicon glyphicon-trash"
                             onClick={() => this.handleDelete(i)}
                     />
                    </div>
                </div>
          </div>
like image 667
Asche Avatar asked Nov 27 '17 09:11

Asche


1 Answers

You need to pass the event object to handleDelete function when you make use of Arrow function as done in your implementation.

You can think of an arrow function like a function that calls another function to which you need to pass the arguments. Event object is a parameter to the arrow function and you indeed need to pass this on to the handleDelete function

onClick={(e) => this.handleDelete(e, i)}

However after this change you still need to bind the deleteTodos function in the parent, since the context of this inside this function won't be that of the React class component, you can do it like

deleteTodos = (i) =>  {
   var lists = this.state.listArr;
   lists.splice(i, 1);
   this.setState({listArr: lists})
 }

or

constructor(props){
    super(props);
    this.state = {
       listArr: [],
    }
    this.deleteTodos = this.deleteTodos.bind(this);
  }
like image 143
Shubham Khatri Avatar answered Oct 15 '22 13:10

Shubham Khatri