Reputation: 711
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
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