Iam stuck with buttons, React

import './App.css';
import React from 'react';
import axios from 'axios';
import Login from './login'
// import List from './List';
export default class PersonList extends React.Component {
  constructor(props){
    super(props);
   // this.handleDelete = this.handleDelete.bind(this);
    this.state = {
    todo: '',
    list:[],
    ids:[],
    showFlag:1
  }}

  handleChange = event => {
    this.setState({ todo: event.target.value });
  }

  handleSubmit = event => {
    
    var payload = this.state;
    if(this.state.list.todo.toString=!null){
    alert("button clicked");
    axios.post("http://localhost:5000/addTodo",payload )
    .then((dat)=>{
      console.log('status : ' + dat.status)
    })
    .catch(()=>{console.log('couldnt have data from backend')})
    }
  
 }

 handleClick= ()=>{
  axios.get("http://localhost:5000/todo")
  .then((dat)=>{
      var temp = dat.data.map(i=>i.todo);
      console.log("temp"+ temp)
      var temp1 = dat.data.map(i=>i.id);
        this.setState({list:temp, showFlag:0, ids:temp1 })
        console.log(this.state.list);
       console.log("here it is");})
  .catch(()=>{console.log('couldnt have data from backend')})
}
 
  render() {
    return (
      <div className="cont">
          <h2> Your Todo List</h2>
          <Login/>
          <form onSubmit={this.handleSubmit} className="form">
         
            <input type="text" name="name" onChange={this.handleChange} placeholder="Add New Todo..."/>
            <button type="submit" className="btn1">Add</button>
          </form>
          <br/>
          <div className="list">
            { this.state.showFlag &&<button onClick={this.handleClick} className="btn2">Show</button>}
            <ul>{this.state.list != null ? this.state.list.map((i,index)=><div className="todos">{i}<button type="button" className="btndel" key={i.id} onClick={ console.log(index)}>Delete</button></div>): "NO tasks! wohoo"}</ul>  
          </div>
      </div>
    )
  }
}

The delete buttons are clicked while they are rendered.

I appreciate your support…

onClick={() => console.log(index)}
1 Like

Like @jenovs pointed, the reason your delete buttons are clicked when they’re rendered is because in onClick you invoke console.log.

Rather you have to pass there a callback function that will be called whenever the button is clicked.

this.handleDeleteClick = this.handleDeleteClick.bind(this);
// ...

handleDeleteClick(value) {
  console.log(value);
}
// ...
<button onClick={handleDeleteClick}>Delete</button>

Or do it inline

// Or inline
<button onClick={() => console.log('whatever')}>Delete</button>
1 Like