Reputation: 797
I have problem to pass callback function between parent and child components. My child component is a list of numbers. I am trying to create a pagination component. I got error message in the Pages.js component when click on the list number -TypeError: undefined has no properties Below is my code, thanks in advance. App.js
class App extends Component {
state = {
CurrentPage: 1,
Items: []
}
handlePageClick = (event) => {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const pageNumbers = 10;
return ( <
Pages pageNumbers = {
pageNumbers
}
onClick = {
this.handlePageClick
}
/>
);
}
}
Pages.js
import React from 'react';
const Pages = ({
pageNumbers,
handlePageClick
}) => {
return (
pageNumbers.map(number => < li key = {
number
}
id = {
number
}
onClick = {
() => this.handlePageClick(number)
} > {
number
} <
/li>)
);
}
}
export default Pages;
Upvotes: 2
Views: 269
Reputation: 692
First off this
is a reserved keyword that can only be used in class components. Second you're passing onClick
prop in the Pages component. So the <li>
tag should call onClick
instead of this.handlePageClick
.
The code below should work without changing anything in the App component.
const Pages = ({
pageNumbers,
onClick
}) => {
return (
pageNumbers.map(number =>
<li key={number}
id={number}
onClick={onClick}
>
{number}
</li>)
);
}
}
Upvotes: 5
Reputation: 687
all you have to do remove the arg event and only set your state with the num you get.
handlePageClick=(num)=> {
this.setState({
currentPage: Number(num)
});
Upvotes: 0