Nikul Panchal
Nikul Panchal

Reputation: 711

react js onclick function doesn't call

I am newbie in react js,I want to do onclick in it, but when i click on button it says this is undefined, can anyone please help me how can i resolve this error, I have placed alert to check if this deleteTask is working or not, but that function doesn't call, here is my full code for that

class PalladiumHub extends React.Component {
  render() {

    return (<tr>
      <td>{this.props.name.id}</td>
      <td>{this.props.name.name}</td>
      <td><button type="button">Edit</button><button onClick={function(e) { this.props.deleteTask(this.props.key) } }>Delete</button></td> 
      </tr>
    )
  }
} //{} {}

class CallCRUD extends React.Component {

  constructor(props) {
    super(props);
    this.deleteTask = this.deleteTask.bind(this);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(res => res.json())
      .then(
        (result) => {

          this.setState({
            isLoaded: true,
            items: result
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }


  deleteTask(index) {   
      alert('sdsd');
      console.log(index);
      //return false;
      let tasks = this.state.items;

      tasks.splice(index,1);
      this.setState({
          items:tasks
      })
  }

  render() {
    console.log(this.state.items);
    return (<table border="1"> <tr><th>ID</th><th>Name</th><th>Action</th></tr> {
      this.state.items.map( (data,index) => {
        return <PalladiumHub name={data} key={data.id} deleteTask ={this.deleteTask} />
      })

    }
      </table>
      );
    }


  }
  ReactDOM.render(
  <CallCRUD />, document.getElementById('root')
);

Upvotes: 1

Views: 313

Answers (2)

Charles Chazz Sohier
Charles Chazz Sohier

Reputation: 101

Hello you need to bind your onClick handler. checkout this page https://reactjs.org/docs/handling-events.html

class PalladiumHub extends React.Component {

onClick = () => {
 this.props.deleteTask(this.props.key)
}
render() {
  return (<tr>
  <td>{this.props.name.id}</td>
  <td>{this.props.name.name}</td>
  <td><button type="button">Edit</button><button onClick={this.onClick.bind(this)}>Delete</button></td> 
  </tr>)
 }
}

Upvotes: 1

Just code
Just code

Reputation: 13801

Do not use functions, they removes this bindings

onClick={function(e) { this.props.deleteTask(this.props.key) } }

change it to

onClick={(e) => this.props.deleteTask(this.props.key)}

also, I would like you to read this

Upvotes: 2

Related Questions